我创建了一个应用程序,使用ALAssetLibrary从iPhone照片文件夹中获取图像。 我可以使用AlAssetLibrary检索文件而无需使用位置服务吗? 我如何避免AlAssetLibrary中的位置服务?
答案 0 :(得分:3)
目前,如果不使用位置服务,则无法访问ALAssetLibrary。你必须使用更有限的UIImagePickerController来解决这个问题。
答案 1 :(得分:1)
如果您只需要库中的一张图片,则上述答案不正确。例如,如果您让用户选择要上传的照片。在这种情况下,您可以使用ALAssetLibrary获取该单个图像,而无需位置权限。
为此,使用UIImagePickerController选择图片;你只需要UIImagePickerController提供的UIImagePickerControllerReferenceURL
。
这样可以让您访问未经修改的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);
}
}];
}