Following code is to save image took from camera into photo album.
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
image = [info objectForKey:UIImagePickerControllerEditedImage];
UIImageWriteToSavedPhotosAlbum(image, self,
#selector(image:finishedSavingWithError:contextInfo:),
nil);
}
How to save Recoded video into photoAlbum?
Check Below code...
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.movie"]){
// Saving the video / // Get the new unique filename
NSString *sourcePath = [[info objectForKey:#"UIImagePickerControllerMediaURL"]relativePath];
UISaveVideoAtPathToSavedPhotosAlbum(sourcePath,nil,nil,nil);
}
- (void)saveMovieToCameraRoll
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:movieURL
completionBlock:^(NSURL *assetURL, NSError *error) {
if (error)
[self showError:error];
else
[self removeFile:movieURL];
dispatch_async(movieWritingQueue, ^{
recordingWillBeStopped = NO;
self.recording = NO;
[self.delegate recordingDidStop];
});
}];
[library release];
}
This is the code snippet from apple example rosywriter. Sould work.
movieURL = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#%#", NSTemporaryDirectory(), #"Movie.MOV"]];
[movieURL retain];
The above lines to create file and path for the video.
- (void) startRecording
{
dispatch_async(movieWritingQueue, ^{
if ( recordingWillBeStarted || self.recording )
return;
recordingWillBeStarted = YES;
// recordingDidStart is called from captureOutput:didOutputSampleBuffer:fromConnection: once the asset writer is setup
[self.delegate recordingWillStart];
// Remove the file if one with the same name already exists
[self removeFile:movieURL];
// Create an asset writer
NSError *error;
assetWriter = [[AVAssetWriter alloc] initWithURL:movieURL fileType:(NSString *)kUTTypeQuickTimeMovie error:&error];
if (error)
[self showError:error];
});
}
This function is used to start recording video into that movieURL file using avassetwriter.
Try below code
- (void)saveVideo:(NSURL *)videoUrl {
NSData *videoData = [NSData dataWithContentsOfURL:videoUrl];
[videoData writeToFile:#"YOUR_PATH_HERE" atomically:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *type = [mediaDict objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:(NSString *)kUTTypeVideo] ||
[type isEqualToString:(NSString *)kUTTypeMovie]) { // movie != video
NSURL *videoURL [mediaDict objectForKey:UIImagePickerControllerMediaURL];
[self saveVideo:videoUrl];
}
}
or you can try this also
Saving the video to the documents directory is as follows
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *tempPath = [documentsDirectory stringByAppendingFormat:#"/vid1.mp4"];
BOOL success = [videoData writeToFile:tempPath atomically:NO];
[picker dismissModalViewControllerAnimated:YES];
}
Related
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];
}
Trying to select image using photo picker and save that image internally in apps folder.
- (void) imagePickerController: (UIImagePickerController *) pickerdidFinishPickingMediaWithInfo: (NSDictionary *) info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToUse;
// Handle a still image picked from a photo album
if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0)
== kCFCompareEqualTo) {
editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
if (editedImage) {
imageToUse = editedImage;
} else {
imageToUse = originalImage;
}
// Do something with imageToUse
//save it
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageName = [documentsDirectory stringByAppendingString:[NSString stringWithFormat:#"%d", myUniqueID]];
NSString *imagePath = [imageName stringByAppendingPathComponent:#".png"];
NSData *webData = UIImagePNGRepresentation(editedImage);
NSError* error = nil;
bool success = [webData writeToFile:imagePath options:NULL error:&error];
if (success) {
// successfull save
imageCount++;
[[NSUserDefaults standardUserDefaults] setInteger:imageCount forKey:#"imageCount"];
NSLog(#"#Success save to: %#", imagePath);
}
else if (error) {
NSLog(#"Error:%#", error.localizedDescription);
}
}
...
}
What I can't figure out is that writeToFile::: returns false but no value is returned in error so I can't figure out whats going wrong. Any help would be greatly appreciated thanks
You're missing a "/". The line:
NSString *imageName = [documentsDirectory stringByAppendingString:[NSString stringWithFormat:#"%d", myUniqueID]];
should be:
NSString *imageName = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%d", myUniqueID]];
And the line that says:
NSString *imagePath = [imageName stringByAppendingPathComponent:#".png"];
should be:
NSString *imagePath = [imageName stringByAppendingPathExtension:#"png"];
Update:
And, shouldn't:
NSData *webData = UIImagePNGRepresentation(editedImage);
be the following?
NSData *webData = UIImagePNGRepresentation(imageToUse);
In my iPhone app, I am taking video using ImagePickerview and storing it to document directory
For iOS4 (device iPod) I can play video stored in document directory but for iOS 5 (device iPad) the same code is not working for playing video.
so for iOS 5 is there any different way for storing and playing video from document directory
(I also tried with library directory)
-(IBAction)saveVideo:(id)sender
{
imagepicker = [[UIImagePickerController alloc] init];
imagepicker.delegate=self;
if([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerSourceTypeCamera])
{
[imagepicker setSourceType:UIImagePickerControllerSourceTypeCamera];
[imagepicker setMediaTypes:[UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera]];
[imagepicker setCameraDevice:UIImagePickerControllerCameraCaptureModeVideo];
[self presentModalViewController:imagepicker animated:YES];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSMutableString *tempPath = [[[info valueForKey:#"UIImagePickerControllerMediaURL"] absoluteString] mutableCopy];
NSString *newPath1 = [NSString stringWithFormat:#"myVideo.mov"];
[tempPath replaceOccurrencesOfString:#"file://localhost/private/" withString:#"/" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempPath length])];
NSFileManager *manager = [NSFileManager defaultManager];
NSError *error = nil;
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], newPath1];
NSString *newPath = [NSString stringWithFormat:#"%#/%#", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], newPath1];
BOOL success = [manager copyItemAtPath:tempPath toPath:newPath error:&error];
if(error){
NSLog(#"New Path: %#", newPath);
NSLog(#"Error: %#", error);
}
if(success)
{
NSLog(#"Succeed");
}
[self dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissModalViewControllerAnimated:YES];
}
-(IBAction)playVideo:(id)sender
{
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [path objectAtIndex:0];
NSString *myDBnew = [documentsDirectory stringByAppendingPathComponent:#"myVideo.mov"];
NSURL *url = [[NSURL alloc] initWithString:myDBnew];
NSLog(#"URL== %#",url);
moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:url];
// [[NSNotificationCenter defaultCenter] addObserver:self
// selector:#selector(moviePlayBackDidFinish:)
// name:MPMoviePlayerPlaybackDidFinishNotification
// object:moviePlayer];
moviePlayer.controlStyle = MPMovieControlStyleDefault;
moviePlayer.shouldAutoplay = YES;
[self.view addSubview:moviePlayer.view];
[moviePlayer setFullscreen:YES animated:YES];
}
What could be wrong?
Here is the code.
If I add the video file into my project and use below code it is playing Video The only thing is it is not playing video from document directory
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"myVideo" ofType:#"mov"]];
moviePlayer = [[MPMoviePlayerController alloc]
initWithContentURL:url];
Even in iTunes via flittering I can see the file:"myVideo.mov", after running the app in device means This codes recording and storing video but not able to read or play.
Here in my code the problem was the way i am creating url
NSURL *url = [[NSURL alloc] initWithString:myDBnew];
which doesn't work for ios5 so i replaced in code by
NSURL *url = [[NSURL alloc] initFileURLWithPath:<#(NSString *)#> isDirectory:<#(BOOL)#>];
I try to save a image from camera or photo album into application directory. But i cant find what i'm doing wrong.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissModalViewControllerAnimated:YES];
theimageView.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
//obtaining saving path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:#"latest_photo.png"];
//extracting image from the picker and saving it
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
NSData *webData = UIImagePNGRepresentation(editedImage);
[webData writeToFile:imagePath atomically:YES];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
if(fileExists){
NSLog(#"image Exists");
}
}
}
Why not use,
UIImage *orgImage = [info objectForKey:UIImagePickerControllerOriginalImage];
And where are failing? Did you get the image properly? or failing to write to document directory?
Check if the file in fact exist in file explorer. Maybe the compiler is right.
can any one help me please
i just want to pick video from iphone which already recorded with help of uiimagepicker controller.
i want to copy my apps document directory.
---------------------------------- prashant
I am unsure of what you mean with no time duration. But you can do the copying/moving in the UIImagePickerDelegate method.
- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSURL *movieURL = (NSURL*)[info objectForKey:UIImagePickerControllerMediaURL];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSURL *saveURL = [NSURL fileURLWithPath:[documentsDirectory stringByAppendingPathComponent:#"movie.mov"]];
NSError *error;
if (!([[NSFileManager defaultManager] moveItemAtURL:movieURL toURL:saveURL error:&error])) {
NSLog(#"Error saving: %#", [error localizedDescription]);
}
[picker dismissModalViewControllerAnimated:YES];
}