use*_*031 5 iphone objective-c uiimagepickercontroller asihttprequest ios
用户从iPhone库中选择图像后UIImagePickerController,我想使用ASIHTTPRequest库将其上传到我的服务器.
我知道ASIHTTPRequest我可以使用文件的URl上传文件,但如何获取图片网址?
我知道我可以得到图像UIImagePickerControllerReferenceURL,看起来像这样:
"assets-library://asset/asset.JPG?id=F2829B2E-6C6B-4569-932E-7DB03FBF7763&ext=JPG"
Run Code Online (Sandbox Code Playgroud)
这是我需要使用的URL吗?
有很多答案建议 UIImageJPEGRepresentation 或 UIImagePNGRepresentation。但是这些解决方案将转换原始文件,而这个问题实际上是关于按原样保存文件。
看起来直接从资产库上传文件是不可能的。但是可以使用 PHImageManager 访问它以获取实际图像数据。就是这样:
Swift 3(Xcode 8,仅适用于 iOS 8.0 及更高版本)
1) 导入照片框架
import Photos
Run Code Online (Sandbox Code Playgroud)
2) 在 imagePickerController(_:didFinishPickingMediaWithInfo:) 中获取资产 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) }
}
}
})
}
}
Run Code Online (Sandbox Code Playgroud)
这将为您提供包含正确名称的文件原样,您甚至可以获取其 UTI 以确定正确的 mimetype(除了通过文件扩展名确定它),同时准备多部分正文进行上传。
获取图像UIImagePickerControllerReferenceUR。下面给出了示例代码
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *representation = [myasset defaultRepresentation];
NSString *fileName = [representation filename];
NSLog(@"fileName : %@",fileName);
CGImageRef ref = [representation fullResolutionImage];
ALAssetOrientation orientation = [[myasset valueForProperty:@"ALAssetPropertyOrientation"] intValue];
UIImage *image = [UIImage imageWithCGImage:ref scale:1.0 orientation:(UIImageOrientation)orientation];
};
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:imageURL
resultBlock:resultblock
failureBlock:nil];
}
Run Code Online (Sandbox Code Playgroud)
注意:它仅适用于iOS 5及更高版本。
| 归档时间: |
|
| 查看次数: |
10349 次 |
| 最近记录: |