最近做一個聊天的項目,需要發送圖片后讀取本地圖片顯示到列表里。剛開始的時候,天真的認為可以用SDWebImage直接加載,然后並不能行。
於是在網上搜了搜,如何根據從相冊獲取的UIImagePickerControllerReferenceURL讀取圖片, 代碼如下:
#import "ViewController.h" #import <AssetsLibrary/AssetsLibrary.h> @interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate> - (IBAction)showImagePickerVC:(id)sender; @property (weak, nonatomic) IBOutlet UIImageView *imageView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; }
彈出圖片選擇器
- (IBAction)showImagePickerVC:(id)sender { UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init]; imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; imagePickerVC.allowsEditing = YES; imagePickerVC.delegate = self; [self presentViewController:imagePickerVC animated:YES completion:nil]; }
回調
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSLog(@"%@", info); NSURL *imagePath = info[@"UIImagePickerControllerReferenceURL"]; if ([[[imagePath scheme] lowercaseString] isEqualToString:@"assets-library"]) { // Load from asset library async dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ @autoreleasepool { @try { ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init]; [assetslibrary assetForURL:imagePath resultBlock:^(ALAsset *asset){ ALAssetRepresentation *rep = [asset defaultRepresentation]; CGImageRef iref = [rep fullScreenImage]; if (iref) { //進行UI修改 dispatch_sync(dispatch_get_main_queue(), ^{ _imageView.image = [[UIImage alloc] initWithCGImage:iref]; }); } } failureBlock:^(NSError *error) { NSLog(@"從圖庫獲取圖片失敗: %@",error); }]; } @catch (NSException *e) { NSLog(@"從圖庫獲取圖片異常: %@", e); } } }); } [picker dismissViewControllerAnimated:YES completion:nil]; }