Приведенный выше ответ неверен, если вам нужно только одно изображение из библиотеки.Например, если у вас есть пользователь, выберите фотографию для загрузки.В этом случае вы можете получить это единственное изображение с помощью ALAssetLibrary, не нуждаясь в разрешениях Location.
Для этого используйте UIImagePickerController, чтобы выбрать картинку;вам просто нужен UIImagePickerControllerReferenceURL
, который предоставляет UIImagePickerController.
Это дает вам преимущество в том, что вы получаете доступ к неизмененному NSData
объекту, который вы затем можете загрузить.потому что перекодирование изображения позже с помощью UIImagePNGRepresentation()
или UIImageJPEGRepresentation()
может удвоить размер вашего файла!
Чтобы представить сборщик:
picker = [[UIImagePickerController alloc] init];
[picker setDelegate:self];
[picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:picker animated:YES completion:nil];
Чтобы получить изображение и / илиданные:
- (void)imagePickerController:(UIImagePickerController *)thePicker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
NSURL *imageURL = [info objectForKey:@"UIImagePickerControllerReferenceURL"];
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:imageURL
resultBlock:^(ALAsset *asset) {
// get your NSData, UIImage, or whatever here
ALAssetRepresentation *rep = [self defaultRepresentation];
UIImage *image = [UIImage imageWithCGImage:[rep fullScreenImage]];
Byte *buffer = (Byte*)malloc(rep.size);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
}
failureBlock:^(NSError *err) {
// Something went wrong; get the image the old-fashioned way
// (You'll need to re-encode the NSData if you ever upload the image)
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
}];
}