我的参数是[String:AnyObjecy]字典,我使用Alamofire上传方法上传图片。当我想用它传递参数时,使用EdFunke建议的方法(https://stackoverflow.com/a/33012955/4919289) 我遇到以下错误:'NSInvalidArgumentException',原因:' - [__ NSCFNumber dataUsingEncoding:
期间:
for (key, value) in params{
print("before key: \(key)")
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
print("after key:\(key)")
}
我想这是因为词典中的值不是字符串,我该如何解决呢?
在2017年2月27日更新了Swift 3
let params = [
//your params
] as [String : Any]
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(self.user.imageData, withName: "your file name", fileName: "your file name with extension", mimeType: "image/jpeg")
for (key, value) in params{
print("key,value: \(key),\(value)")
let stringValue = value as! String
multipartFormData.append(stringValue.data(using: .utf8)!, withName: key)
}
}, to:"your url")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
//Print progress
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
//print response.result
print(response.result)
}
case .failure(let encodingError):
print("in faulure")
print(encodingError)
self.presentAlertView(title: "Error", message: "cannot register", buttonText: "OK")
//print(encodingError.description)
break
//print encodingError.description
}
}
答案 0 :(得分:0)
如果是UIImage
你可以这样做
for (key, value) in params{
if let image = value as? UIImage {
if let imageData: NSData = UIImageJPEGRepresentation(image, 1){
multiPartFormData.appendBodyPart(data: imageData, name: "file", fileName: "key.jpg", mimeType: "image/jpg")
}
} else {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}