ios 7 video saving issue - iphone

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);
}

Related

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];
}

AVAssetExportSession outputfile

How should the AVAssetExportSession output file look like? I'm trying to compress a video from an ALAsset item and it doesn't work. I'm guessing the output file has something to do with it.
Here's the code i'm using:
NSString *destinationPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Movie"];
[self convertVideoToLowQualityWithInputURL:asset.defaultRepresentation.url outputURL:[NSURL URLWithString:destinationPath]];
- (void)convertVideoToLowQualityWithInputURL:(NSURL*)inputURL outputURL:(NSURL*)outputURL {
if([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithContentsOfURL:outputURL encoding: 0 error:Nil]]) [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
AVURLAsset *assetAV = [AVURLAsset URLAssetWithURL:inputURL options:nil];
NSLog(#"url string from asset: %#", assetAV.URL);
NSLog(#"output url: %#", [outputURL absoluteString]);
[[NSFileManager defaultManager] createFileAtPath:[outputURL path] contents:nil attributes:nil];
NSLog(#"duration: %lld", assetAV.duration.value); //it logs a valid value, so it's all good so far
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:assetAV presetName:AVAssetExportPresetLowQuality];
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
[exportSession exportAsynchronouslyWithCompletionHandler:^(void) {
if (exportSession.status == AVAssetExportSessionStatusCompleted) {
NSLog(#"success");
} else {
NSLog(#"error: %#", [exportSession error]);
//error: Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo=0x2023b720 {NSLocalizedDescription=The operation could not be completed, NSUnderlyingError=0x2023bb70 "The operation couldn’t be completed. (OSStatus error -12780.)", NSLocalizedFailureReason=An unknown error occurred (-12780)}
}
}];
}
Can someone please help me?
UPDATE:
Found the solution. As I thought the problem was the output file so here is the code for generating a valid one:
NSUInteger count = 0;
NSString *filePath = nil;
do {
NSString *extension = ( NSString *)UTTypeCopyPreferredTagWithClass(( CFStringRef)AVFileTypeQuickTimeMovie, kUTTagClassFilenameExtension);
NSString *fileNameNoExtension = [[asset.defaultRepresentation.url URLByDeletingPathExtension] lastPathComponent];
NSString *fileName = [NSString stringWithFormat:#"%#-%#-%u",fileNameNoExtension , AVAssetExportPresetLowQuality, count];
filePath = NSTemporaryDirectory();
filePath = [filePath stringByAppendingPathComponent:fileName];
filePath = [filePath stringByAppendingPathExtension:extension];
count++;
} while ([[NSFileManager defaultManager] fileExistsAtPath:filePath]);
NSURL *outputURL = [NSURL fileURLWithPath:filePath];
Your issue is [NSURL URLWithString:destinationPath] and only that. You need to use [NSURL fileURLWithPath:xxx] like you did in your solution. Posting this just to clarify that that is the only problem.

Attach sound file from gallery in iOS

Is it possible to access sound files gallery just like image gallery in my iOS app, I have tried searching on net but have not found any good content about it.
You can refer to the AddMusic sample application from Apple to see how its done...
Yes you can upload it to server. Use below code :
When you select a song from picker
- (void)mediaPicker: (MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
MPMediaItem *song = nil ;
[self dismissModalViewControllerAnimated:YES];
if ([mediaItemCollection count] < 1)
{
return;
}
[song release];
song = [[[mediaItemCollection items] objectAtIndex:0] retain];
//song.accessibilityHin
[self uploadMusicFile:song];
}
- (void) uploadMusicFile:(MPMediaItem *)song
{
// Init audio with playback capability
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
NSURL *assetURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
// to get uniqe time interval
[[NSDate date] timeIntervalSince1970];
// convert this ti string
NSTimeInterval seconds = [[NSDate date] timeIntervalSince1970];
NSString *intervalSeconds = [NSString stringWithFormat:#"%0.0f",seconds];
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset presetName: AVAssetExportPresetPassthrough];
exporter.outputFileType = #"public.mpeg-4";
NSString *exportFile = [[NSString alloc] initWithString:[DOCUMENTS_FOLDER stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.mp4",intervalSeconds]]];
NSURL *exportURL = [[NSURL fileURLWithPath:exportFile] retain];
exporter.outputURL = exportURL;
[exporter exportAsynchronouslyWithCompletionHandler:
^{
NSData *data = [NSData dataWithContentsOfURL:exportURL];
// Here your upload code
}];
}

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];
}

Saving a Video to the Photo Library - iPhone SDK

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");
}
}];
});
});