2017-01-16 105 views
0

遷移對我來說簡直就是一場噩夢。我從以前的版本雨燕/的iOS/Alamofire如何在Alamofire4中進行multipartFormData上傳?

let intVal = 0 

Alamofire.upload(.POST, url, headers: ["StringValue": intVal, "StringValue2": "StringValue3"], multipartFormData: { mpfd in 
     let image = self.profileImageView.image! 
     let imageData = UIImageJPEGRepresentation(image, 0.8)! 
     mpfd.appendBodyPart(data: imageData, name: "image", fileName: "custom_image.jpg", mimeType: "image/jpeg") 
     }, encodingCompletion: { result in 

      switch result { 
      case .success(let request, _, _): 
       let response = request.response 
       print("response from image change: \(response)") 
       print("Successfully changed pro pic") 
      case .failure/*(let encodingError)*/: 
       print("Failed to change pro pic") 
      } 

    }) 

的這個老代碼,但現在的Xcode是給我一個錯誤說「不明確提及成員「上傳(_:到:方法:標題)」,但我不知道我是否可以信任這些錯誤消息,因爲Alamofire會觸發並且現在拋出數千個錯誤,例如encoding: .json現在是JSONEncoding.default,但是Xcode告訴我錯誤是「函數調用中的額外方法」。所以,我想大多數其他錯誤的解決方案是切換的方法和URL參數

Alamofire.upload(url, method: .post, headers ...) 

但是,這也不能正常工作。我應該如何重寫這個新的Swift/Alamofire?

+0

[相關Q​​&A](http://stackoverflow.com/questions/41401913/cannot-invoke-append-with-an-argument-list- of-type-string-withname-string /) – dfri

回答

1

有一個在Alamofire的測試套件的一個示例:https://github.com/Alamofire/Alamofire/blob/9688b16f0546b97b16c775c75f42b3f4bfacc78e/Tests/UploadTests.swift#L244

guard let image = self.profileImageView.image, 
    let imageData = UIImageJPEGRepresentation(image, 0.8) else { 
    return 
} 

Alamofire.upload(
    multipartFormData: { multipartFormData in 
    mpfd.append(imageData, withName: "image", fileName: "custom_image.jpg", mimeType: "image/jpeg") 
    }, 
    to: url, 
    headers: ["Header": value, "Another_Header": value2], 
    encodingCompletion: { result in 
    // Whatever 
    } 
) 
+0

我會在哪裏放一個'headers'參數,就像我原來的那樣?這實際上是我的主要問題 –

+0

這是'upload'函數的可選參數。見https://github.com/Alamofire/Alamofire/blob/2b65bfe6608a236772b4151b0ec9e82a51a22131/Source/Alamofire.swift#L376 - 我編輯了包含標題的答案 – Estel