2015-12-02 60 views
4

我設法與上傳多形式的數據Alamofire上傳文件:Alamofire - 如何與多上傳進度和完成關閉

Alamofire.upload(.POST, "api.myservice.com", headers: myheaders, multipartFormData: { (multipartFormData:MultipartFormData) -> Void in 

    multipartFormData.appendBodyPart(data: json, name: "metadata", mimeType: "application/json") 
    multipartFormData.appendBodyPart(data: self.data, name: "document", fileName: "photo.png", mimeType: "image/png") 

}, encodingMemoryThreshold: 10 * 1024 * 1024) { (result:Manager.MultipartFormDataEncodingResult) -> Void in 
} 

,但我看不到的方式來跟蹤上傳進度,並有上載完成(或失敗)後調用完成塊。 Alamofire有沒有辦法做到這一點?

注:我知道上傳的進度是可能的,但我正在研究多部分形式的數據。

回答

14

這裏是一個辦法有完成,失敗和進度關閉(感謝我的同事對我點的解決方案):

Alamofire.upload(.POST, absPath(), headers: headers(), multipartFormData: { (multipartFormData:MultipartFormData) -> Void in 

    multipartFormData.appendBodyPart(data: json, name: "metadata", mimeType: "application/json") 
    multipartFormData.appendBodyPart(data: self.data, name: "document", fileName: "photo.png", mimeType: "image/png") 

    }, encodingMemoryThreshold: 10 * 1024 * 1024, encodingCompletion: { (encodingResult) -> Void in 
     switch encodingResult { 
     case .Success(let upload, _, _): 
      upload.responseJSON { response in 
       // success block 
     } 
      upload.progress { _, totalBytesRead, totalBytesExpectedToRead in 
       let progress = Float(totalBytesRead)/Float(totalBytesExpectedToRead) 
       // progress block 
      } 
     case .Failure(_): 
      // failure block 
     } 
}) 
4

接受的答案是偉大的。這一個也包括參數:

let image = UIImage(named: "big.jpg")! 
let imageData = UIImageJPEGRepresentation(image, 1) 

let coupon = textBox?.text ?? "NO coupon" 
let uploadUrl = "http://example.com/upload.php" 
// define parameters 
let parameters : [String: String] = ["one":"some param", "two":"some other param"] 

Alamofire.upload(.POST, uploadUrl, headers: nil, 
    multipartFormData: { multipartFormData in 
     multipartFormData.appendBodyPart(data: imageData!, name: "cannotBeBlank", fileName: "image.zip", mimeType: "image/png") 

     // import parameters 
     for (key, value) in parameters { 
      multipartFormData.appendBodyPart(data: value.data!, name: key) 
     } 
    }, encodingCompletion: { encodingResult in 
     switch encodingResult { 
      case .Success(let upload, _, _): 
       upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in 
        print("1) \(bytesWritten) 2) \(totalBytesWritten) 3) \(totalBytesExpectedToWrite)") 

        // This closure is NOT called on the main queue for performance 
        // reasons. To update your ui, dispatch to the main queue. 
        dispatch_async(dispatch_get_main_queue()) { 
         print("Total bytes written on main queue: \(totalBytesWritten)") 
        } 
       } 


       upload.responseData(self.handleResponse) 
      case .Failure: 
       self.handleError() 
     } 
}) 
+1

這適用於我。謝謝! –

+0

很高興聽到它。希望它在Swift 3中不會打破太多! –