Spe*_*edy 5 nsurl uiimagepickercontroller ios swift alamofire
从我正在开发的iOS应用程序上传图像到我的服务器时出现问题.我正在使用Alamofire和a UIImagePickerController.
里面的didFinishPickingMediaWithInfo委托方法我节省了用户选择的文件NSURL从info[UIImagePickerControllerReferenceURL]一个命名的变量self.imageNSURL.
将此传递给Alamofires就这样上传multipartFormData方法(几乎是他们的文档中的标准复制和粘贴)
Alamofire.upload(
.POST,
URLString: "http://app.staging.acme.com/api/users/\(id)/picture",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: self.imageNSURL, name: "image")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { request, response, JSON, error in
println(JSON)
}
case .Failure(let encodingError):
println(encodingError)
}
}
)
Run Code Online (Sandbox Code Playgroud)
我得到的错误是
Error Domain=com.alamofire.error Code=-1000 "The operation couldn’t be completed. The URL does not point to a file URL: assets-library://asset/asset.JPG?id=00000000-0000-0000-0000-000000000000&ext=JPG" UserInfo=0x00000000000 {NSLocalizedFailureReason=The URL does not point to a file URL: assets-library://asset/asset.JPG?id=00000000-0000-0000-0000-000000000000&ext=JPG}
Run Code Online (Sandbox Code Playgroud)
请注意,我在这篇文章的回复中已经确认了ID,实际的错误信息包含有效的错误信息.
小智 3
这是因为从info[UIImagePickerControllerReferenceURL]该 URL 返回的 URL 指向 asset-library/asset,这是由于沙箱造成的。因此您无法使用此 URL 访问该文件,这就是为什么 alamofire 抱怨您的 URL 不是文件 URL。为了解决这个问题,您可以使用multipartFormData.appendBodyPart(data: data, name: name)此方法将要发送的数据直接作为NSData. 完整代码示例:
let imagePicked = info[UIImagePickerControllerOriginalImage]
let imageExtenstion = info[UIImagePickerControllerReferenceURL]
// imageExtenstion will be "asset.JPG"/"asset.JPEG"/"asset.PNG"
// so we have to remove the asset. part
var imagePickedData : NSData
switch imageExtenstion {
case "PNG": imagePickedData = UIImagePNGRepresentation(imagePicked)!
// compressionQuality is a float between 0.0 and 1.0 with 0.0 being most compressed with lower quality and 1.0 least compressed with higher quality
case "JPG", "JPEG": imagePickedData = UIImageJPEGRepresentation(image, compressionQuality)!
}
Alamofire.upload(.POST, YOUR_URL, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imagePickedData, name: imageName)
}, encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { request, response, JSON, error in
print(JSON)
}
case .Failure(let encodingError):
print(encodingError)
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2588 次 |
| 最近记录: |