Swift 4 - Get an Upload Image Progress using URLSession

后端 未结 2 574
生来不讨喜
生来不讨喜 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:32

    For image with multple Paramaters Uploading to server. Try this code Alamofire. Its going to work.

    Alamofire.upload(multipartFormData: { (multipartFormData : MultipartFormData) in
                let count = imageToUpload.count
                for (key, value) in parameters {
                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
                }
                for i in 0..<count{
                    let image:UIImage = self.loadImage(imageToUpload[i])
                    if let imageData = image.jpegData(compressionQuality: 0.5) {
                        let imageName  = "image[\(i)]"
                        multipartFormData.append(imageData as Data, withName:imageName , fileName: imageToUpload[i], mimeType: "image/jpeg")
                    }
                }
            }, usingThreshold: UInt64.init(), to: serviceUrl, method: .post, headers: headers)  { (result) in
                switch result {
                case .success(let upload, _ , _):
                    upload.uploadProgress(closure: { (progress) in
                        print("uploding: \(progress.fractionCompleted)")
                    })
                    upload.responseJSON { response in
                        if response.result.isFailure {
                            if let err = response.error{
                                print(err)
                            }
                            return
                        }
    
                        guard let jsonData = response.result.value else {                           
                            return
                        }
                        //
    
                        do{
                            let json = try JSONSerialization.jsonObject(with: response.data as! Data, options: [])
                            print("josnResposne:\(json)")
    
                        } catch let parsingError {
                            print("Error", parsingError)
                        }
    
                    }
                case .failure(let encodingError):
                    print("failed")
                    print(encodingError)                                        
                }
            }
    
    0 讨论(0)
  • 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
        }
    
    0 讨论(0)
提交回复
热议问题