Download a file with NSURLSession in Swift

我的梦境 提交于 2019-11-30 23:12:12
derdida

I am at the moment on a project with a background Download Manager, and here are a few things, how I solved that:

if you are using the NSURLSessionDownloadDelegate you need to implement the following methods:

func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!) 

func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) 

func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!) 

I have done this with this call:

var session:NSURLSession!


    var sessionConfiguration:NSURLSessionConfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.company")
    sessionConfiguration.HTTPMaximumConnectionsPerHost = 5

    self.session = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)

// on download

var downloadTask:NSURLSessionDownloadTask = self.session.downloadTaskWithURL(NSURL.URLWithString("urlfromyourfile"))
downloadTask.resume()

// on error:

func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {

    if(error != nil) {

        println("Download completed with error: \(error.localizedDescription)");

    } else {

        println("Download finished successfully");

    }

}

Here you find a good tutorial (i used lots of code from that tutorial and wrote it new with swift)

http://www.appcoda.com/background-transfer-service-ios7/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!