我已經使用Alamofire創建了用於分段上傳的函數。
調用此函數傳遞Web服務URL,參數和圖像。
func WSPostAPIMultiPart(_ aStrULR:String,
param: [String: Any],
image : UIImage?,
controller: UIViewController,
successBlock: @escaping (_ response:[String : Any]?) -> Void,
failureBlock: @escaping (_ error: Error?) -> Void) {
var dictHeaders : HTTPHeaders = [String : String]()
if (Alamofire.NetworkReachabilityManager()?.isReachable)!{
Alamofire.upload(
multipartFormData: { MultipartFormData in
let JSONData: Data? = try? JSONSerialization.data(withJSONObject: param, options: .prettyPrinted)
MultipartFormData.append(JSONData!, withName: "json")
if image != nil{
MultipartFormData.append(UIImageJPEGRepresentation(image!, 0.5)!, withName: "profile_image",fileName: "image.jpeg", mimeType: "image/jpeg")
// withName : You will pass the key name required by your server
}
}, to: aStrULR ,method : .post , headers : dictHeaders) { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
if let value = response.result.value {
let dictResponse = JSON(value).dictionaryObject
successBlock(dictResponse)
}
}
case .failure(let error):
failureBlock(error)
}
}
}else{
print("NO INTERNET CONNECTIVITY")
}
}
對於視頻:只是通過videoURL一個額外的參數和附加:
MultipartFormData.append(videoUrl, withName: "profileVideo", fileName: "video.mp4", mimeType: "video/mp4")
希望它能幫助:)
[上傳圖像的可能的複製與斯威夫特參數](https://stackoverflow.com/questions/26162616/upload-image-with-parameters-in-swift) – Jaydeep
你可以用alamofire –