iphone - 如何上传从 UIImagePickerController 获取的图像

标签 iphone objective-c ios uiimagepickercontroller asihttprequest

用户使用 UIImagePickerController 从 iPhone 库中选择图像后,我想使用 ASIHTTPRequest 库将其上传到我的服务器。

我知道使用 ASIHTTPRequest 我可以上传带有文件 URl 的文件,但是我如何获取图像 URL?

我知道我可以获得图像 UIImagePickerControllerReferenceURL,它看起来像这样:

"assets-library://asset/asset.JPG?id=F2829B2E-6C6B-4569-932E-7DB03FBF7763&ext=JPG"

这是我需要使用的 URL 吗?

最佳答案

有很多答案建议使用 UIImageJPEGRepresentation 或 UIImagePNGRepresentation。但是这些解决方案将转换原始文件,而这个问题实际上是关于按原样保存文件。

看来直接从 Assets 库上传文件是不可能的。但是可以使用 PHImageManager 访问它以获取实际图像数据。方法如下:

Swift 3(Xcode 8,仅适用于 iOS 8.0 及更高版本)

1) 导入照片框架

import Photos

2) 在 imagePickerController(_:didFinishPickingMediaWithInfo:) 中获取 Assets URL

3) 使用 fetchAssets(withALAssetURLs:options:) 获取资源

4) 使用requestImageData(for:options:resultHandler:) 获取实际图像数据。在此方法的结果处理程序中,您将拥有数据以及文件的 URL(可以在模拟器上访问 URL,但遗憾的是在设备上无法访问 - 在我的测试中,startAccessingSecurityScopedResource() 始终返回 false)。但是,此 URL 仍然可用于查找文件名。

示例代码:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    dismiss(animated: true, completion: nil)
    if let assetURL = info[UIImagePickerControllerReferenceURL] as? URL,
        let asset = PHAsset.fetchAssets(withALAssetURLs: [assetURL], options: nil).firstObject,
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first,
        let targetURL = Foundation.URL(string: "file://\(documentsPath)") {

        PHImageManager.default().requestImageData(for: asset, options: nil, resultHandler: { (data, UTI, _, info) in
            if let imageURL = info?["PHImageFileURLKey"] as? URL,
                   imageData = data {
                    do {
                        try data.write(to: targetURL.appendingPathComponent(imageURL.lastPathComponent), options: .atomic)

                        self.proceedWithUploadFromPath(targetPath: targetURL.appendingPathComponent(imageURL.lastPathComponent))

                   } catch { print(error) }
                }
            }
        })
    }
}

这将按原样为您提供文件,包括其正确的名称,您甚至可以在准备上传的多部分正文时获取其 UTI 以确定正确的 mimetype(除了通过文件扩展名确定它之外)。

关于iphone - 如何上传从 UIImagePickerController 获取的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12138484/

相关文章:

iphone - UITableView : detecting click on '-' button in edit mode

iphone - NSManagedObjectContext 无法删除其他上下文中的对象

ios - UIView 不会以编程方式移动

ios - 如何将水平滚动添加到 UIView?

ios - 通知如何适应 iOS VIPER 架构?

ios - 向 UIImageView 添加一个复杂的边框

iPhone - NSKeyedUnarchiver 内存泄漏

ios - Multpeer连接-检查附近是否所有对等连接,并尝试重新连接

ios - SFSafariViewController初始化方法强制使用iOS11支持的版本

html - 我在哪里可以获得 libxml2.2.dylib?