Swift 4 - Get an Upload Image Progress using URLSession

后端 未结 2 582
生来不讨喜
生来不讨喜 2020-12-22 02:04

I have this kind of code below

func upload(){
    let img = UIImage(named: \"1\")
    let imgData = UIImageJPEGRepresentation(img!, 1)
    let data = imgData         


        
2条回答
  •  天涯浪人
    2020-12-22 02:47

    for getting progress use following delegate method of URLSession, You can get progress in didReceiveData method

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
    
            //here you can get full lenth of your content
            expectedContentLength = Int(response.expectedContentLength)
            println(expectedContentLength)
            completionHandler(NSURLSessionResponseDisposition.Allow)
        }
    
        func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
    
    
            buffer.appendData(data)
    
            let percentageDownloaded = Float(buffer.length) / Float(expectedContentLength)
            progress.progress =  percentageDownloaded
        }
    
        func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
            //use buffer here.Download is done
            progress.progress = 1.0   // download 100% complete
        }
    

提交回复
热议问题