this question has answer here:
note: not duplicate because working in swift, not objective c, please don't mark such.
i have following code download file:
func loadfileasync(url: nsurl, name: string, completion:(path:string, error:nserror!) -> void) { let documentsurl = nsfilemanager.defaultmanager().urlsfordirectory(.documentdirectory, indomains: .userdomainmask).first nsurl! let destinationurl = documentsurl.urlbyappendingpathcomponent(name) tempdocpath = destinationurl.path! if nsfilemanager().fileexistsatpath(destinationurl.path!) { print("file exists [\(destinationurl.path!)]") completion(path: destinationurl.path!, error:nil) } else { let sessionconfig = nsurlsessionconfiguration.defaultsessionconfiguration() let session = nsurlsession(configuration: sessionconfig, delegate: nil, delegatequeue: nil) let request = nsmutableurlrequest(url: url) request.httpmethod = "get" let task = session.datataskwithrequest(request, completionhandler: { (data: nsdata?, response: nsurlresponse?, error: nserror?) -> void in if (error == nil) { if let response = response as? nshttpurlresponse { print("response=\(response)") if response.statuscode == 200 { if data!.writetourl(destinationurl, atomically: true) { print("file saved [\(destinationurl.path!)]") completion(path: destinationurl.path!, error:error) } else { print("error saving file") let error = nserror(domain:"error saving file", code:1001, userinfo:nil) completion(path: destinationurl.path!, error:error) } } } } else { print("failure: \(error!.localizeddescription)"); completion(path: destinationurl.path!, error:error) } }) task.resume() } }
what need have find bytes read , bytes expected read in order display progress view?
don't use datataskwithrequest(_, completionhandler:)
method create data task. instead use datataskwithrequest(_)
, set delegate, , implement urlsession(_, datatask:,data:)
delegate method , monitor size of data blocks receive.
Comments
Post a Comment