我是这样使用Alamofire上传图片的。
编辑:这是经过编辑的代码......
for img in images {
let url = "http:my url"
let headers = [
"Accept": "application/json",
"Authorization": self.accessToken
]
if let imageData = (UIImageJPEGRepresentation(img, 0.6)) {
let parameters: [String: String] =
[
"seller_id": "\(self.mySellerId)",
"offline_id": self.prodID,
"is_default": "1",
"sequence": "\(sequenceCount)"
]
Alamofire.upload(multipartFormData: {(multipartFormData) in
let filePath = NSURL(fileURLWithPath: url)
print(imageData)
multipartFormData.append (imageData, withName: "image", fileName: "\(Date().timeIntervalSince1970).jpg", mimeType: "image / jpg")
for (key, value ) in parameters {
print(key,value)
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}
}, to: url, method: .post, headers: headers)
{ (result) in
switch result {
case .success(let upload, _,_ ):
upload.uploadProgress(closure: { (progress) in
UILabel().text = "\((progress.fractionCompleted * 100)) %"
print (progress.fractionCompleted * 100)
})
upload.responseJSON { response in
if let JSON = response.result.value {
print(JSON)
}else{
print("Error")
}
}
case .failure(let encodingError):
print(encodingError)
break
}
}
}
}
在for (key, value) in parameters...
部分中,for循环遍历所有值。但当它到达图像数据部分时,它崩溃说Could not cast value of type 'Foundation.Data' (0x10787b9f0) to 'Swift.String'
应该给出什么,以便可以修复错误..?
答案 0 :(得分:0)
您正在将parameters
字典中的所有值转换为String
,字典中的第一个条目为"product_image"
,并且它将imageData作为值并且类型为{{ 1}}。
我会这样做,不再强行施放。
Data
您还可以检查值是否已经for (key, value) in parameters {
if let v = value as? String, let valueAsData = v.data(using: .utf8) {
multipartFormData.append(valueAsData, withName: key )
}
}
类型,并且只需将其添加为:
Data