在今天的项目开发中用到一个图片上传的接口, 需要将本地图片的保存路径上传到服务器. 最初的想法是先获取图片的名称, 再根据图片名获取图片的完整路径, 最后上传.
获取相册中图片的信息需要导入 <AssetsLibrary/AssetsLibrary.h>头文件, 并在UIImagePickerController 的代理方法中实现如下方法:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
//先获取asset在ALAssetsLibrary库中的url
NSURL *imageUrl = [info valueForKey:UIImagePickerControllerReferenceURL];
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
//根据url获取asset信息, 并通过block进行回调
[assetsLibrary assetForURL:imageUrl resultBlock:^(ALAsset *asset) {
ALAssetRepresentation *representation = [asset defaultRepresentation];
NSString *imageName = representation.filename;
NSLog(@"imageName:%@", imageName);
} failureBlock:^(NSError *error) {
NSLog(@"%@", [error localizedDescription]);
}];
}
后来发现根据图片名并不能获取图片在系统中的路径, 所以上面做的并没有什么卵用. 最后只能先将相册中的图片保存本地沙盒路径中, 再将沙盒路径作为作为参数上传. 此法才为问题的正解.
UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *doucumentDirectory = paths[0];
NSString *fullPath = [doucumentDirectory stringByAppendingPathComponent:@"photo.jpg"];
[UIImageJPEGRepresentation(image, 0.5) writeToFile:fullPath atomically:YES];