Download a file with NSURLSession in Swift

前端 未结 1 2063
臣服心动
臣服心动 2021-01-06 05:17

i have like 2 problems here , first i cant set NSURLSessionDownloadDelegate with a swift project, compiler says

Type \'ViewController\' does not conform to          


        
相关标签:
1条回答
  • 2021-01-06 05:31

    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/

    0 讨论(0)
提交回复
热议问题