Saving a Video to the Photo Library - iPhone SDK - iphone

Is there any way for me to save a video in the Documents directory to the Photos Library? I have the link of the video in the documents directory, I just don't know how to save it to the Photos app.
Thanks,
Kevin

If you are saving it in a local directory first, then you can save it as..
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary writeVideoAtPathToSavedPhotosAlbum:url completionBlock:^(NSURL *assetURL, NSError *error){
if(error) {
NSLog(#"error while saving to camera roll %#",[error localizedDescription]);
} else {
//For removing the back up copy from the documents directory
NSError *removeError = nil;
[[NSFileManager defaultManager] removeItemAtURL:url error:&removeError];
NSLog(#"%#",[removeError localizedDescription]);
}
}];

Use the UISaveVideoAtPathToSavedPhotosAlbum function.

Try this
You can also use this code to download and save video from internet to Photos.
NSURL *videoUrl = [NSURL URLWithString:[NSString stringWithFormat:#"Your Video Url or Path"]];
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(q, ^{
NSData *videoData = [NSData dataWithContentsOfURL:videoUrl];
dispatch_async(dispatch_get_main_queue(), ^{
// Write it to cache directory
NSString *videoPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"file.mov"];
[videoData writeToFile:videoPath atomically:YES];
// After that use this path to save it to PhotoLibrary
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:videoPath] completionBlock:^(NSURL *assetURL, NSError *error)
{
if (error)
{
NSLog("Error");
}
else
{
NSLog("Success");
}
}];
});
});

Related

ios 7 video saving issue

Im saving the video to photolibrary.Its works for previous ios ,In ios 7
videoAtPathIsCompatibleWithSavedPhotosAlbum this line allways false
here is my code any one can help me.
NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:#"NewmergeVideo.mov"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPathDocs];
if (fileExists) {
[[NSFileManager defaultManager] removeItemAtPath: myPathDocs error:NULL];
}
NSURL *url = [NSURL fileURLWithPath:myPathDocs];
NSLog(#"%#",url);
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
exporter.outputURL=url;
//[exporter setVideoComposition:MainCompositionInst];
exporter.outputFileType = AVFileTypeQuickTimeMovie;
[exporter exportAsynchronouslyWithCompletionHandler:^
{
dispatch_async(dispatch_get_main_queue(), ^{
[self _exportDidFinish:exporter];
});
}];
here is save code
- (void)_exportDidFinish:(AVAssetExportSession*)session
{
NSURL *outputURL = session.outputURL;
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
NSLog(#"%#",outputURL);
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:outputURL]) {
[library writeVideoAtPathToSavedPhotosAlbum:outputURL
completionBlock:^(NSURL *assetURL, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
NSLog(#"writeVideoToAssestsLibrary failed: %#", error);
}else{
NSLog(#"Writing3");
}
});
}];
}
[library release];
}
in previous ios nsurl
file://localhost/var/mobile/Applications/99B72CBA-A426-4F04-B7B2-2B61F0B0C513/Documents/NewmergeVideo.mov
in ios 7 nsurl
file:///var/mobile/Applications/791244EE-771B-46C9-BD57-BA0BE6CACD3C/Documents/NewmergeVideo.mov
You can Use this code to save file.(It's work correctly)
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(outputURL))
{
UISaveVideoAtPathToSavedPhotosAlbum(outputURL, self, #selector(video:didFinishSavingWithError:contextInfo:), nil);
}
-(void) video: (NSString *) videoPath didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
if(error)
NSLog(#"Finished saving video with error: %#", error);
}

NSData writeToFile works on simulator but not on device

In my iphone app I am downloading some number of images from the web. It doesn't matter if it blocks the UI thread, in fact it needs to block UI thread till fully downloaded. Once done, I notify the UI to wake up and display them.
My (simplified) code goes like this:
for (int i=0; i<10; i++)
{
//call saveImageFromURL (params)
}
//Call to Notify UI to wake up and show the images
+(void) saveImageFromURL:(NSString *)fileURL :(NSString *)destPath :(NSString *)fileName
{
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
NSFileManager * fileManager = [NSFileManager defaultManager];
BOOL bExists, isDir;
bExists = [fileManager fileExistsAtPath:destPath isDirectory:&isDir];
if (!bExists)
{
NSError *error = nil;
[fileManager createDirectoryAtPath:destPath withIntermediateDirectories:YES attributes:nil error:&error];
if (error)
{
NSLog(#"%#",[error description]);
return;
}
}
NSString *filePath = [destPath stringByAppendingPathComponent:fileName];
[data writeToFile:filePath options:NSAtomicWrite error:nil];
}
When I am done with my for loop, I am pretty sure that all images are stored locally. And it works fine in simulator.
However it does not work well on my device. UI wakes up before images are stored. And almost all images seem empty.
What am I doing wrong?
Check that if your device can download those images, visit the image URLs in Mobile Safari to test. dataWithContentsOfURL: will return nil OR it's not a correct image data, like 404 not found
Log errors of [data writeToFile:filePath] to see the details of saving .
After some research, I used AFHttpClient enqueueBatchOfHTTPRequestOperations to accomplish multiple file downloads.
Here is how it goes:
//Consider I get destFilesArray filled with Dicts already with URLs and local paths
NSMutableArray * opArray = [NSMutableArray array];
AFHTTPClient *httpClient = nil;
for (id item in destFilesArray)
{
NSDictionary * fileDetailDict = (NSDictionary *)item;
NSString * url = [fileDetailDict objectForKey:#"fileURL"];
if (!httpClient)
httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:url]];
NSString * filePath = [photoDetailDict objectForKey:#"filePath"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
[opArray addObject:operation];
}
[httpClient enqueueBatchOfHTTPRequestOperations:opArray progressBlock:nil completionBlock:^(NSArray *operations)
{
//gets called JUST ONCE when all operations complete with success or failure
for (AFJSONRequestOperation *operation in operations)
{
if (operation.response.statusCode != 200)
{
NSLog(#"operation: %#", operation.request.URL);
}
}
}];

Access URL of recently saved image

I am using the
UIImageWriteToSavedPhotosAlbum(image,nil,nil,nil);
to save image but i want to know where it is getting saved, mean referenceURL and name of saved image..
You can get it using ALAssetsLibrary
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:myCGImage metadata:nil completionBlock:^(NSURL* assetURL, NSError* error)
{
if (error.code == 0) {
NSLog(#"URL %#", assetURL);
[library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
NSLog(#"Filename %#", [[asset defaultRepresentation] filename]);
}
failureBlock:^(NSError* error) {
NSLog(#"failed to retrieve image asset:\nError: %# ", [error localizedDescription]);
}];
}else {
NSLog(#"saved image failed.\nerror code %i\n%#", error.code, [error localizedDescription]);
}
}];

Getting NSData from an NSURL

I am trying to upload a photo from my app into a web service.
The flow I am attempting to create is as follows:
User takes photo with camera
Photo is saved to camera roll under a custom album
URL of the saved photo is given to my store
Store attempts to upload the photo to a web service.
I am trying to use NSData *data = [NSData dataWithContentsOfURL:[item assetURL]] where item is a model that contains the URL concerned. But this line is not producing a data when I log it even if it produces a URL: "assets-library://asset/asset.PNG?id=28DBC0AC-21FF-4560-A9D6-5F4BCA190BDB&ext=PNG"
The code snippets are as follows:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:^(void){
[library writeImageToSavedPhotosAlbum:image.CGImage orientation:image.imageOrientation completionBlock:^(NSURL* assetURL, NSError* error) {
BCard *card = [[BCard alloc]init];
//error handling
if (error!=nil) {
NSLog(#"[ERROR] - %#",error);
return;
}
//add the asset to the custom photo album
[library addAssetURL: assetURL
toAlbum:#"Business Cards"
withCompletionBlock:^(NSError *error) {
if (error!=nil) {
NSLog(#"Custom Album Error: %#", [error description]);
}
}];
[card setAssetURL:assetURL];
[[BCardStore sharedStore]addToQueue:card];
int index = [[[BCardStore sharedStore]getQueue]count]-1;
[[BCardStore sharedStore]uploadItemAtIndex:index withProgressBlock:nil withExitBlock:nil];
}];
}];
}
and
-(void)uploadItemAtIndex:(NSUInteger)index withProgressBlock:(progressBlock)pBlock withExitBlock:(exitBlock)eBlock
{
BCard *item = [uploadQueue objectAtIndex:index];
NSURL *url = [NSURL URLWithString:#"http://192.168.0.116:8080"];
NSData *data = [NSData dataWithContentsOfURL:[item assetURL]];
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
numberedName = numberedName +1;
NSString *name = [NSString stringWithFormat:#"%d",numberedName];
NSLog(#"%#",[item assetURL]);
//upload data using AFNetworking here
}
The snippet [library addAssetUrl:NSUrl toAlbum:NSString withCompletionBlock:^(NSError *error)] came from the category I found here.
Am I really getting the right URL here or am I using dataWithContentsOfURL incorrectly?
The only way is You can retrieve the UIImage from Photo-Library using ALAsset URL and convert in to NSData.
Add ALAssetLibrary
Import ALAssetLibrary header file
-(void)uploadItemAtIndex:(NSUInteger)index
withProgressBlock:(progressBlock)pBlock
withExitBlock:(exitBlock)eBlock
{
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep;
if([myasset defaultRepresentation] == nil) {
return;
} else {
rep = [myasset defaultRepresentation];
}
CGImageRef iref = [rep fullResolutionImage];
dispatch_sync(dispatch_get_main_queue(), ^{
UIImage *myImage = [UIImage imageWithCGImage:iref];
NSData *data = //convert the myImage to NSData
BCard *item = [uploadQueue objectAtIndex:index];
NSURL *url = [NSURL URLWithString:#"http://192.168.0.116:8080"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
numberedName = numberedName +1;
NSString *name = [NSString stringWithFormat:#"%d",numberedName];
//upload data using AFNetworking here
});//end block
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(#"Cant get image - %#",[myerror localizedDescription]);
};
NSURL *asseturl =
[NSURL URLWithString:[self.photoPath objectAtIndex:[arrayIndex intValue] ]];
//using ARC , you have to declare ALAssetsLibrary as member variable
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:assetURL
resultBlock:resultblock
failureBlock:failureblock];
}

iPhone Save Movie Clip - Doesn't work on 3GS

The following code works on iPad and iPhone/iPod 4, but will not work on 3G/3GS, meaning the movie clips won't save. The os on our test 3G/3GS devices is > 4.0.
-(void)processMovieClipSave:(NSConnection*)connection
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
SystemSoundID snapShot;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"tapsound" ofType:#"wav"]],&snapShot);
AudioServicesPlaySystemSound(snapShot);
NSData* data = [NSData dataWithContentsOfURL:moviePlayerController.contentURL];
NSString* path = nil;
NSString *paths = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
path = [paths stringByAppendingPathComponent:#"/src.mp4"];
[data writeToFile:path atomically:NO];
NSURL *clipURL = [NSURL URLWithString:path];
//NSLog(#"Save Clip URL: %#",[clipURL absoluteString]);
ALAssetsLibrary* library = [[[ALAssetsLibrary alloc]init]autorelease];
[library writeVideoAtPathToSavedPhotosAlbum:clipURL completionBlock:^(NSURL *assetURL, NSError *error)
{
NSMutableDictionary *dict = nil;
if (error)
{
dict = [[NSMutableDictionary alloc]init];
[dict setObject:error forKey:#"error"];
}
[self performSelectorOnMainThread:#selector(onMovieClipSaved:) withObject:dict waitUntilDone:NO];
if (dict)
[dict release];
}];
[pool release];
}