I am using the UIImagePickerController in two cases
In the first case, when I choose an image form the library, I can easily get the URL in the delegate method:
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// Get the URL
NSURL *url = [info valueForKey:UIImagePickerControllerReferenceURL];
...
}
But when I take a new picture, the image is not yet in the photo library and has no URL yet. So, I first need to add the image in the Library. But then, how to get the URL of the new asset?
Here is my code to add the image in the Photo Library
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// Get the image
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// Add the image in the library
[[PHPhotoLibrary sharedPhotoLibrary]
performChanges:^
{
// Request creating an asset from the image.
PHAssetChangeRequest *createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
// Get the URL of the new asset here ?
...
}
completionHandler:^(BOOL success, NSError *error)
{
if (!success) { ...; return; }
// Get the URL of the new asset here ?
...
}
];
}
I didn't find the way to get URL, but maybe localIdentifier can help you do the same work.
use
NSString* localId = [[assetChangeRequest placeholderForCreatedAsset] localIdentifier];
to get the local ID and get the image later.
__block NSString* localId;
// Add it to the photo library
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
if (self.assetCollection) {
PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:self.assetCollection];
[assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]];
}
localId = [[assetChangeRequest placeholderForCreatedAsset] localIdentifier];
} completionHandler:^(BOOL success, NSError *error) {
PHFetchResult* assetResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[localId] options:nil];
if (!success) {
NSLog(@"Error creating asset: %@", error);
} else {
PHFetchResult* assetResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[localId] options:nil];
PHAsset *asset = [assetResult firstObject];
[[PHImageManager defaultManager] requestImageDataForAsset:asset options:nil resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
UIImage* newImage = [UIImage imageWithData:imageData];
self.imageView.image = newImage;
}];
}
}];