2

NOTE: This is not a duplicate because I am working in swift, not Objective C, so please don't mark it as such.

I have the following code to download a file:

func loadFileAsync(url: NSURL, name: String, completion:(path:String, error:NSError!) -> Void) {
    let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL!
    let destinationUrl = documentsUrl.URLByAppendingPathComponent(name)
    tempDocPath = destinationUrl.path!
    if NSFileManager().fileExistsAtPath(destinationUrl.path!) {
        print("file already 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 do I need to have to find the bytes read and bytes expected to read in order to display a progress view?

Mike Schmidt
  • 683
  • 3
  • 10
  • 31
  • NSURLSession has delegate protocols for accessing progress. – Putz1103 Jul 21 '16 at 18:07
  • @Putz1103 I need the answer in swift- that is Objective C – Mike Schmidt Jul 21 '16 at 18:10
  • Converting between the two is not a ridiculously hard task, but I will search it out for you. – Putz1103 Jul 21 '16 at 18:11
  • @Putz1103 thanks because I really only know Swift, and barely any Objective C so even if it is not that difficult it is for me – Mike Schmidt Jul 21 '16 at 18:12
  • Here is a link to the correct delegate protocol. It has example function declarations in both Objective-C and Swift. https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSessionDataDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionDataDelegate/URLSession:dataTask:didReceiveData: – Putz1103 Jul 21 '16 at 18:12
  • Here's a tutorial with exact code examples and how to implement them for downloading a file in Swift with progress tracking: https://www.raywenderlich.com/110458/nsurlsession-tutorial-getting-started – Putz1103 Jul 21 '16 at 20:15
  • That tutorial worked great! Thanks for the help @Putz1103 – Mike Schmidt Jul 21 '16 at 21:36

1 Answers1

1

Don't use the dataTaskWithRequest(_, completionHandler:) method to create your data task. Instead use dataTaskWithRequest(_), set a delegate, and implement the URLSession(_, dataTask:,data:) delegate method and monitor the size of the data blocks you receive.

Duncan C
  • 115,063
  • 19
  • 151
  • 241