I'm saving a video obtained from AVCaptureVideoDataOutput with AVAsset using writeVideoAtPathToSavedPhotosAlbum like below.
NSString* filename = [NSString stringWithFormat:#"capture%d.mp4", _currentFile];
NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];
NSURL* url = [NSURL fileURLWithPath:path];
dispatch_async(dispatch_get_main_queue(), ^{
[_encoder finishWithCompletionHandler:^{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:url completionBlock:^(NSURL *assetURL, NSError *error){
NSLog(#"save completed");
}];
}];
});
However after saving the video I want to get the 'saved videos info' back like we get with following when using UIImagePickerController.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissViewControllerAnimated:YES completion:NULL];
NSLog(#"there");
// Handle a movie capture
NSString *type = info[UIImagePickerControllerMediaType];
NSURL *videoURL = info[UIImagePickerControllerMediaURL];
//do things with that info
}
Here is the code to save the video and add that video in custom album, and then inform where it has been saved.
[library writeVideoAtPathToSavedPhotosAlbum:videoInputUrl completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
NSLog(#"Video could not be saved");
}
else{
[library assetForURL:assetURL
resultBlock:^(ALAsset *asset) {
// assign the photo to the album
[groupToAddTo addAsset:asset];
NSLog(#"Added Successfully %# to %#", [[asset defaultRepresentation] filename], albumName);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Success" message:#"Video Saved to xyz Album." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil, nil];
[alert show];
}
failureBlock:^(NSError* error) {
NSLog(#"failed to retrieve image asset:\nError: %# ", [error localizedDescription]);
}];
}
}];
Hope this help you...:)
Related
We are making a chat app and for video thumbnail we use the following code. But it crashes in random cases.
NSArray *arrjid = [jid componentsSeparatedByString:#"#"];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMddHHmmss"];
NSString *strdate = [dateFormatter stringFromDate:[NSDate date]];
NSString *strname = [NSString stringWithFormat:#"%#_%#_file.mov",arrjid[0],strdate];
NSString *videoPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:strname];
[videoData writeToFile:videoPath atomically:YES];
if([[NSFileManager defaultManager] fileExistsAtPath:videoPath])
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:videoPath] completionBlock:^(NSURL *assetURL, NSError *error) {
}];
}
Every time it crashes on the writeVideoAtPathToSavedPhotosAlbum line and it gives only "bad access error".
Does anyone have an idea related to this?
ALAssetsLibrary library method writeVideoAtPathToSavedPhotosAlbum:completionBlock: is deprecated, you can use PHPhotoLibrary instead.
try this
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL: yourVideoURlHere];
} completionHandler:^(BOOL success, NSError *error) {
if (success) {
//Do Something
}
}];
Also check if you have Photo Library usage description in info plist with following key
NSPhotoLibraryUsageDescription
UPDATE
For fetching thumbnail from video you can use AVAssetImageGenerator class from AVFoundation framework
- (UIImage *) thumbnailFromVideoAtURL:(NSURL *) contentURL {
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:contentURL options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform = YES;
NSError *err = NULL;
CMTime time = CMTimeMake(1, 60);
CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:&err];
UIImage *thumbnail = [[UIImage alloc] initWithCGImage:imgRef];
CGImageRelease(imgRef);
return thumbnail;
}
Make sure you have permission to save to the photo gallery.
Import the Photos class:
#import <Photos/Photos.h>
Then check for Photo Library Authorization
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusAuthorized) {
//OK to save your video
[self ContinueDownload];
}
else if (status == PHAuthorizationStatusDenied) {
// Access has been denied.
[self ShowAlert];
}
else if (status == PHAuthorizationStatusNotDetermined) {
// Access has not been determined.
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusAuthorized) {
//OK to save your video
[self ContinueDownload];
}
else {
// Access has been denied.
[self ShowAlert];
}
}];
}
else if (status == PHAuthorizationStatusRestricted) {
// Restricted access
}
//Show an alert if access is denied
-(void)ShowAlert {
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:#"Gallery Access denied"
message:#"You can grant access in\nSettings/Privacy/Photos\nif you change your mind."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* OKButton = [UIAlertAction
actionWithTitle:#"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//[self dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:OKButton];
[self presentViewController:alert animated:YES completion:nil];
}
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.
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];
}
}];
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!