ios - Swift 3 DispatchQueue.global (download images from Firebase and UI frozen) -
i have problema method:
func downloadimages(uid: string, indice: int) { dispatchqueue.global(qos: .background).async { let refbbdd = firdatabase.database().reference().child("users").child(uid) refbbdd.observesingleevent(of: .value, with: { snapshot in let snapshotvalue = snapshot.value as? nsdictionary let profileimageurl = snapshotvalue?.value(forkey: "profileimageurl") as! string let storage = firstorage.storage() var reference: firstoragereference! if(profileimageurl == "") { return } print("before") reference = storage.reference(forurl: profileimageurl) reference.downloadurl { (url, error) in let data = nsdata(contentsof: url!) let image = uiimage(data: data! data) print("image yet dowload ") self.citas[indice].image = image dispatchqueue.main.async(execute: { () -> void in self.tableview.reloadrows(at: [indexpath(row: indice, section: 0)], with: .none) //self.tableview.reloaddata() print("image loaded") }) } print("after") }) } } i want download images in background mode. want follow using app, ui has frozen until methods not entry in reloadrows.
is possible run in true background mode , can follow using app??
trace program:
before after before after ... before after before after image yet dowload --> here start ui frozen image loaded image yet dowload image yet dowload ... image yet dowload image yet dowload image loaded image loaded ... image loaded image loaded image yet dowload ------> here ui not frozen image loaded
the problem caused line: let data = nsdata(contentsof: url!). constructor of nsdata should used read contents of local url (a file path on ios device), since synchronous method , hence if call download file url, blocking ui long time.
i have never used firebase, looking @ documentation, seems me using wrong method download file. should using func getdata(maxsize size: int64, completion: @escaping (data?, error?) -> void) -> storagedownloadtask instead of func downloadurl(completion: @escaping (url?, error?) -> void), since documentation states, latter "retrieves long lived download url revokable token", doesn't download contents of url itself.
moreover, shouldn't force unwrapping values in completion handler of network request. network requests can fail reasons other programming error, if don't handle errors gracefully, program crash.
Comments
Post a Comment