I want to saved an image in my photo albums, however I had succesfully saved the image but now I want to get the URL which would be my local URL that would open the image If I passes that to UIImage. I'm unable to get the saved image url as of error that "expression not allowed". How can I get the LOCAL URL of my saved image in iOS.
My Tried:
-(NSString *) imageSave: (UIImage *)image
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation)image.imageOrientation completionBlock:^(NSURL *assetURL, NSError *error )
{
[library assetForURL:assetURL resultBlock:^(ALAsset *asset )
{
self.temp1 = [NSString stringWithFormat:#"%#",assetURL];
NSLog(#"SAVED!");
}
failureBlock:^(NSError *error )
{
self.temp1 = [NSString stringWithFormat:#"NO"];
NSLog(#"Error Saving Image!!!");
}];
}];
return self.temp1;
}
I tried by ma making a property but that returns null.
Try following code that may help you.
UIImage *viewImage = YOUR UIIMAGE // ---
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Request to save the image to camera roll
[library writeImageToSavedPhotosAlbum:[viewImage CGImage] orientation:(ALAssetOrientation)[viewImage imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
NSLog(#"error");
} else {
NSLog(#"url %#", assetURL);
NSString *myString = [assetURL absoluteString];
}
}];
Related
I have developed a camera application with all basic functionalities. When you take a picture that image will be saved in the newly created folder but if I delete an image in my application its not getting deleted in that folder. I need to delete it permanently using objective C
You can't delete something from gallery, you can just use photos from gallery in your app and save to Gallery, but iOS doesn't give such permissions to other app as deleting something from Gallery.(if it is not jailbroken) There is no such functionality in WhatsApp too(or I can't see it).
FOR iOS 8.0+
You can only delete the ALAsset which is created by your app with document API [ALAsset setImageData:metadata:completionBlock:]
Saving Image photo.jpg to gallery by,
ALAssetsLibrary *lib = [ALAssetsLibrary new];
UIImage *image = [UIImage imageNamed:#"photo.jpg"];
[lib writeImageToSavedPhotosAlbum:image.CGImage metadata:#{} completionBlock:^(NSURL *assetURL, NSError *error) {
NSLog(#"Write image %# to asset library. (Error %#)", assetURL, error);
}];
You can Find this in "Saved Photos" album.
To delete:
ALAssetsLibrary *lib = [ALAssetsLibrary new];
[lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop) {
if(asset.isEditable) {
[asset setImageData:nil metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
NSLog(#"Asset url %# should be deleted. (Error %#)", assetURL, error);
}];
}
}];
} failureBlock:^(NSError *error) {
}];
ALAssetLibrary is Deprecated since iOS 9.0, you can use
PHPhotoLibrary Instead.
iOS 9.0+
// Delete asset from library
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest deleteAssets:assetArray];
} completionHandler:completionHandler];
In collection view didselect method i getting the url of selected image
UIImage *viewImage = _myma; // --- mine was made from drawing context
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Request to save the image to camera roll
[library writeImageToSavedPhotosAlbum:[viewImage CGImage] orientation:(ALAssetOrientation)[viewImage imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
NSLog(#"error");
} else {
NSLog(#"url %#", assetURL);
NSString *urlString = [assetURL absoluteString];
selectedurl = urlString;
//NSLog(#"myurl%#", selectedurl);
}
the in action button used to delete the selected images
NSURL *deleteurl = [NSURL URLWithString:selectedurl];
NSArray *arrDelete = [[NSArray alloc] initWithObjects:deleteurl , nil];
NSEnumerator *asset = [PHAsset fetchAssetsWithALAssetURLs:arrDelete options:nil];
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest deleteAssets:asset];// asset is an array
} completionHandler:^(BOOL success, NSError *error) {
NSLog(#"Finished Delete asset. %#", (success ? #"Success." : error));
if (success) {
NSLog(#"deleted");
}
}];
In my app I used edit pic and saved in custom folder in Gallery called "Fab". now is there anything to delete that image from folder? I have found different solution but they require asset URL. I used Photos framework so how to get asset url for particular image for deletion ?
PHAsset *tempPhasset = [_arrImageForAssetCameraRoll objectAtIndex:index]; // here pass your PHasset that you want to delete .
NSString *localStr=tempPhasset.localIdentifier;
NSRange range = [localStr rangeOfString:#"/"];
NSString *newString = [localStr substringToIndex:range.location];
NSString *appendedString=[NSString stringWithFormat:#"%#%#%#",#"assets-library://asset/asset.JPG?id=",newString,#"&ext=JPG"];
NSLog(#"%# phasset ",appendedString);
NSURL *deleteurl = [NSURL URLWithString:appendedString];
NSArray *arrDelete = [[NSArray alloc] initWithObjects:deleteurl , nil];
PHFetchResult *asset = [PHAsset fetchAssetsWithALAssetURLs:arrDelete options:nil];
[asset enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"%#",[obj class]);
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
BOOL req = [obj canPerformEditOperation:PHAssetEditOperationDelete];
if (req) {
NSLog(#"true");
[PHAssetChangeRequest deleteAssets:#[obj]];
}
} completionHandler:^(BOOL success, NSError *error) {
NSLog(#"Finished Delete asset. %#", (success ? #"Success." : error));
if (success) {
NSLog(#"delete successfully");
}else{
NSLog(#"delete Cancel");
}
}];
Any query about my code then put comment .
Happy Coding.
Try this below code
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:[viewImage CGImage] orientation:(ALAssetOrientation)[viewImage imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
NSLog(#"error");
} else {
NSLog(#"url %#", assetURL);
}
}];
will return url for saved image.
Problem:
I've got some trouble using writeImageDataToSavedPhotosAlbum:metadata:completionBlock: of AVAssetsLibrary
Question:
I want to use this over writeImageToSavedPhotosAlbum:metadata:completionBlock: to avoid possible compression of the photo library
Here is my code sample below :
CFDataRef pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.imageView.image.CGImage));
uint8_t *data = (uint8_t *)CFDataGetBytePtr(pixelData);
NSData *dataTOSave = [NSData dataWithBytesNoCopy:data length:CFDataGetLength(pixelData) freeWhenDone:NO];
ALAssetsLibrary *assetLib = [[ALAssetsLibrary alloc] init];
[assetLib writeImageDataToSavedPhotosAlbum:dataTOSave metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
NSLog(#"error %#", error);
}];
Error log in the completion block print null, but nothing appears in the photo library of my iPhone.
But now, if I used writeImageToSavedPhotosAlbum:metadata:completionBlock: it works great :
ALAssetsLibrary *assetLib = [[ALAssetsLibrary alloc] init];
[assetLib writeImageToSavedPhotosAlbum:[self.imageView.image CGImage] metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
NSLog(#"error %#", error);
}];
Error log still print null, and the image appears in the photo Library.
Note that I did this test with a small jpg image (250*333).
Does someone have any idea of why the first sample not working ? And why no errors is shown in the completion block ?
i am trying to save UIImage in the photos album of iPad with a custom name for each UIImage. I searched a lot and i realised that it is possible if i save them at the documents directory but not in the photos album. I was wondering if you could suggest a solution for that , please? Thank you in advance, best regards
To save it with a custom name I would use the following code:
// I do this in the didFinishPickingImage:(UIImage *)img method
// Build NSData in memory from the btnImage...
NSData* imageData = UIImageJPEGRepresentation(img, 1.0);
// Save to the default Apple (Camera Roll) folder.
[imageData writeToFile:#"/private/var/mobile/Media/DCIM/100APPLE/customImageFilename.jpg" atomically:NO];
In order to save an screenshot in the device in a custom album name use the following code:
- (void)createScreenshotAndSaveInACustomAlbum {
DebugLog(#"");
if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
} else {
UIGraphicsBeginImageContext(self.view.bounds.size);
}
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library addAssetsGroupAlbumWithName:#"My Photo Album" resultBlock:^(ALAssetsGroup *group) {
// Checks if group previously created
if(group == nil){
// Enumerate albums
[library enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:^(ALAssetsGroup *g, BOOL *stop)
{
// If the album is equal to our album
if ([[g valueForProperty:ALAssetsGroupPropertyName] isEqualToString:#"My Photo Album"]) {
// Save image
[library writeImageDataToSavedPhotosAlbum:UIImagePNGRepresentation(image) metadata:nil
completionBlock:^(NSURL *assetURL, NSError *error) {
// Then get the image asseturl
[library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
// Put it into our album
[g addAsset:asset];
} failureBlock:^(NSError *error) {
}];
}];
}
} failureBlock:^(NSError *error){ }];
} else {
// Save image directly to library
[library writeImageDataToSavedPhotosAlbum:UIImagePNGRepresentation(image) metadata:nil
completionBlock:^(NSURL *assetURL, NSError *error) {
[library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
[group addAsset:asset];
} failureBlock:^(NSError *error) { }];
}];
}
} failureBlock:^(NSError *error) { }];
}
Hope this helps!
I capture still image and save to camera roll with AV Foundation like this:
- (void) captureStillImage
{
AVCaptureConnection *stillImageConnection =
[self.stillImageOutput.connections objectAtIndex:0];
if ([stillImageConnection isVideoOrientationSupported])
[stillImageConnection setVideoOrientation:AVCaptureVideoOrientationPortrait];
[self.stillImageOutput
captureStillImageAsynchronouslyFromConnection:stillImageConnection
completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
{
if (imageDataSampleBuffer != NULL)
{
NSData *imageData = [AVCaptureStillImageOutput
jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
UIImage *image = [[UIImage alloc] initWithData:imageData];
[library writeImageToSavedPhotosAlbum:[image CGImage]
orientation:(ALAssetOrientation)[image imageOrientation]
completionBlock:^(NSURL *assetURL, NSError *error){
}];
}
else
{
NSLog(#"Error capturing still image: %#", error);
}
}
];
}
These images from my App when check again in Photos App don't have info about city name.
How to capture still image and save with its location name which can be display in photos app?
Thanks for help!
From the Docs : captureStillImageAsynchronouslyFromConnection
handler
A block to invoke after the image has been captured. The block
parameters are as follows: imageDataSampleBuffer The data that was
captured. The buffer attachments may contain metadata appropriate to
the image data format. For example, a buffer containing JPEG data may
carry a kCGImagePropertyExifDictionary as an attachment. See
ImageIO/CGImageProperties.h for a list of keys and value types.
So using that you can get the meta data.
CFDictionaryRef metaDict = CMCopyDictionaryOfAttachments(NULL, imageDataSampleBuffer, kCMAttachmentMode_ShouldPropagate);
CFMutableDictionaryRef mutable = CFDictionaryCreateMutableCopy(NULL, 0, metaDict);
NSDictionary *metaDict = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:self.currentLocation.coordinate.latitude], kCGImagePropertyGPSLatitude,
#"N", kCGImagePropertyGPSLatitudeRef,
[NSNumber numberWithFloat:self.currentLocation.coordinate.longitude], kCGImagePropertyGPSLongitude,
#"E", kCGImagePropertyGPSLongitudeRef,
#"04:30:51.71", kCGImagePropertyGPSTimeStamp,
nil];
NSLog(#"%#",metaDict);
CFDictionarySetValue(mutable, kCGImagePropertyGPSDictionary, (__bridge const void *)(metaDict));
and when saving to Asset Library use this method to add the meta data
[library writeImageToSavedPhotosAlbum:[image CGImage] metadata:mutable completionBlock: nil];