ImagePicker captures photo, but can't save to Album - ios

I already wrote this code to make a profile photo for my app and it doesn't work. Been searching for different sources and couldn't find any.Please help. I can take a photo but it doesn't get saved on the Album and a photo can't be uploaded or saved on the UIImageView for the profile.
#import "ViewController.h"
#interface ViewController ()
{
UIImage *originalImage;
}
#property(nonatomic, weak) IBOutlet UIImageView *selectedImageView;
#property(nonatomic, weak) IBOutlet UIBarButtonItem *saveButton;
#end
#implementation ViewController
#synthesize selectedImageView, saveButton;
- (IBAction)photoFromAlbum
{
UIImagePickerController *photoPicker = [[UIImagePickerController alloc] init];
photoPicker.delegate = self;
photoPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:photoPicker animated:YES completion:NULL];
}
- (IBAction)photoFromCamera
{
UIImagePickerController *photoPicker = [[UIImagePickerController alloc] init];
photoPicker.delegate = self;
photoPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:photoPicker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)photoPicker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
self.saveButton.enabled = YES;
originalImage = [info valueForKey:UIImagePickerControllerOriginalImage];
[self.selectedImageView setImage:originalImage];
// [photoPicker dismissModalViewControllerAnimated:YES];
}
- (IBAction)saveImageToAlbum
{
UIImageWriteToSavedPhotosAlbum(self.selectedImageView.image, self, #selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
NSString *alertTitle;
NSString *alertMessage;
if(!error)
{
alertTitle = #"Image Saved";
alertMessage = #"Image saved to photo album successfully.";
}
else
{
alertTitle = #"Error";
alertMessage = #"Unable to save to photo album.";
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:self
cancelButtonTitle:#"Okay"
otherButtonTitles:nil];
[alert show];
}
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: #"test.png"] ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
#end

Related

Save a picture after the application is closed

There is a simple application, on the storyboard added UIImageView and button
Button opens the photo gallery, and I choose an image and eventually it appears on the UIimaeView
But when I kill the application snapshot is not saved What to do?
this my code :
-(IBAction)takePic:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
self.image.image=[info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:nil];
}
ok. try this:
#import "ViewController.h"
#import AssetsLibrary;
#interface ViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
#property (weak, nonatomic) IBOutlet UIImageView *imageView;
#property (strong, nonatomic) UIImagePickerController *picker;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSURL *selectedImageURL = [NSURL URLWithString:[userDefaults objectForKey:#"selectedImageURL"]];
if (selectedImageURL) {
[self getImageFromAssetsAtURL:selectedImageURL completion:^(UIImage *image, NSError *error) {
if (!error && image) {
self.imageView.image = image;
}
}];
}
}
- (IBAction)pickImage:(UIButton *)sender {
[self presentViewController:self.picker animated:YES completion:nil];
}
- (UIImagePickerController *)picker {
if (!_picker) {
_picker = [UIImagePickerController new];
_picker.delegate = self;
_picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
}
return _picker;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
UIImage *selectedImage = info[UIImagePickerControllerOriginalImage];
NSURL *selectedImageURL = info[UIImagePickerControllerReferenceURL];
// set image
self.imageView.image = selectedImage;
// save image url
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:selectedImageURL.absoluteString forKey:#"selectedImageURL"];
[userDefaults synchronize];
// dismiss
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)getImageFromAssetsAtURL:(NSURL *)imageURL completion:(void (^)(UIImage *, NSError *))completion {
ALAssetsLibrary *library = [ALAssetsLibrary new];
[library assetForURL:imageURL resultBlock:^(ALAsset *asset) {
UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]];
completion(image, nil);
} failureBlock:^(NSError *error) {
completion(nil, error);
}];
}
#end
since the AssetsLibrary is deprecated as of iOS 9.0 you could and should use the Photos framework instead. you have to import it...
#import Photos;
and change the getImageFromAssetsAtURL... method to the following:
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[imageURL] options:nil];
if (result.count == 1) {
PHAsset *asset = result.firstObject;
[[PHImageManager defaultManager] requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
UIImage *selectedImage = [UIImage imageWithData:imageData];
completion(selectedImage, nil);
}];
} else {
completion(nil, nil);
}
Finally I used this code.
-(void)viewDidLoad {
[super viewDidLoad];
[self loadDefaultImage];
}
-void)viewDidAppear:(BOOL)animated
{
[self loadDefaultImage];
}
- (IBAction)TakePic:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = info[UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *image = info[UIImagePickerControllerOriginalImage];
//append filename to document directory url
NSURL *urlSave = [[self getDocumentsPathURL] URLByAppendingPathComponent:#"imagee"];
//do something to previously taken image (in this case: delete it)
if ([[NSFileManager defaultManager] fileExistsAtPath:urlSave.path]) {
[[NSFileManager defaultManager] removeItemAtPath:urlSave.path error:nil];
}
//save image to document directory
[UIImagePNGRepresentation(image) writeToFile:urlSave.path atomically:YES];
//optional: save image to photo library
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
}
-(NSURL *)getDocumentsPathURL
{
//document directory of app
return [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
}
-(void)loadDefaultImage
{
NSURL *urlImage = [[self getDocumentsPathURL] URLByAppendingPathComponent:#"imagee"];
if ([[NSFileManager defaultManager] fileExistsAtPath:urlImage.path]) {
NSData *dataFile = [[NSFileManager defaultManager] contentsAtPath:urlImage.path];
UIImage *image = [UIImage imageWithData:dataFile];
[_imageView setImage:image];
}
else {
NSLog(#"Image not found");
}
}

copy gallery image to project files Objective-C

I am new in Objective-C and I want choose one image from a Gallery and I want get the name and the extension and copy that image to my project folder.
Use UIimagePicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
if ([mediaTypeStr isEqualToString:#"photo"])
{
if ([info objectForKey:UIImagePickerControllerOriginalImage])
{
// images = [NSMutableArray arrayWithCapacity:[info count]];
_images = [[NSMutableArray alloc]init];
UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];;
img =[self scaleAndRotateImage:img];
[_images addObject:img];
// Save Photo to library only if it wasnt already saved i.e. its just been taken
[self.alAsstlibrary saveImage:img toAlbum:#"FOlder name" completion:^(NSURL *assetURL, NSError *error)
{
if (error!=nil)
{
//NSLog(#"Big error: %#", [error description]);
}
} failure:nil];
}
else
{
//NSLog(#"UIImagePickerControllerReferenceURL = %#", info);
}
}
[picker dismissViewControllerAnimated:YES completion:Nil];
}
write these in viewdidload or on the buttons click event as per your need..
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = NO;//by writing YES here you can edit image also..
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
imgview=[[UIImageView alloc]initWithFrame:CGRectMake(x+y, y, width, height)];
[imgview setTag:i];
imgview.contentMode = UIViewContentModeScaleAspectFill;
[imgview setClipsToBounds:YES];
[self.view addSubview:imgview];
write these in your .m file..
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//if you write picker.allowsEditing = YES; than write info[UIImagePickerControllerEditedImage] in BELOW line....
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
imgview.image = chosenImage;//set selected image in your imageview
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:NULL];
}
i hope it helps..
To achieve this follow these steps.
Get the image
- (void) getPicture:(id)sender
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = (sender == myPic) ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypeSavedPhotosAlbum;
[self presentModalViewController:picker animated:YES];
[picker release];
}
You will get the image in imagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage (UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
[self save:image];
[picker dismissModalViewControllerAnimated:YES];
}
Save image in documents
-(void)save:(UIImage*)image
{
NSData *pngData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
}
Get document path
- (NSString *)documentsPathForFileName:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
return [documentsPath stringByAppendingPathComponent:name];
}
Get the Image
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:pngData];

How to show and play captured photos and videos,Audios in ios [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi i am beginner in Ios and in my project i have given facility for users capturing photos and videos and Audios from camera and i am storing their "paths" in array lists and i am displays them in one table-list so for everything is ok
But here my main requirement is when i click table-list rows then if there is image file it must be shows or if there is video it must be play audio also have to play as like videos for this i have written some code here photos and videos are playing fine but audio files giving problem what did i do here wrong?
my code:-
#import "ViewController2.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController2 ()
{
NSMutableArray * arr_mediaType;
UIImagePickerController *imagePicker;
UIImage *snap;
NSData *data1;
NSMutableArray * arr_media;
MPMoviePlayerController * moviePlayer;
UIImageView *dot;
AVAudioRecorder * _audioRecorder;
AVAudioPlayer * player;
}
#end
#implementation ViewController2
#synthesize maintablelist;
- (void)viewDidLoad {
arr_mediaType = [[NSMutableArray alloc]init];
arr_media = [[NSMutableArray alloc]init];
maintablelist.delegate = self;
maintablelist.dataSource = self;
[super viewDidLoad];
}
- (IBAction)takePicture:(id)sender {
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
- (IBAction)takeVideo:(id)sender {
NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:#"iPhone Simulator"] || [model isEqualToString:#"iPad Simulator"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Angry!!!" message:#"No Camera found!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.videoMaximumDuration = 10;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
}
- (IBAction)takeAudio:(id)sender {
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString]; // to get unique name
NSString *soundfile = [NSString stringWithFormat:#"sound%#.m4a",fileName];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:soundfile];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(#"FilePath:%#",soundFileURL);
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
NSError *error = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
error:nil];
_audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSetting
error:&error];
if (error)
{
NSLog(#"error: %#", [error localizedDescription]);
}
else {
NSLog(#"ok");
[arr_media addObject:soundFilePath];
[_audioRecorder record];
[maintablelist reloadData];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
[mediaType isEqual: #"Photos"];
[arr_mediaType addObject:#"Photos"];
snap = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"Pic-%#.png", fileName]];
NSData *data = UIImageJPEGRepresentation(snap, 1.0);
[data writeToFile:filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:nil];
NSLog(#"So finally path is%#",filePath);
[arr_media addObject:filePath];
[maintablelist reloadData];
}
else {
[mediaType isEqual: #"Videos"];
[arr_mediaType addObject:#"Video"];
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"videoURL --->>> %#",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"video%#.mov", fileName]];
BOOL success = [videoData writeToFile:filePath atomically:NO];
[arr_media addObject:filePath];
NSLog(#"videoURLPath --->>> %#",filePath);
[picker dismissViewControllerAnimated:YES completion:nil];
[maintablelist reloadData];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr_mediaType.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cells=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:nil];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cells];
}
cell.textLabel.text = [arr_media objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Photos"]) {
[moviePlayer.view removeFromSuperview];
dot =[[UIImageView alloc] initWithFrame:CGRectMake(40,320,240,128)];
dot.image = [UIImage imageNamed:[arr_media objectAtIndex:indexPath.row]];
[self.view addSubview:dot];
}
else if([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Videos"])
{
[dot removeFromSuperview];
NSURL*theurl=[NSURL fileURLWithPath:[arr_media objectAtIndex:indexPath.row]];
moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:theurl];
[moviePlayer.view setFrame:CGRectMake(40, 320, 240, 128)];
[moviePlayer prepareToPlay];
[moviePlayer setShouldAutoplay:NO];
[self.view addSubview:moviePlayer.view];
}
else
{
NSString *filePath = [arr_media objectAtIndex:indexPath.row];
NSData *soundData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:filePath]];
player = [[AVAudioPlayer alloc] initWithData:soundData error:nil];
[player setDelegate:self];
[player play];
}
}
#end
Here, I have modified your piece of code. First of all, there is no need of different arrays to store images and videos. You can access it from one. Simillarly, there is no need of storing media types in two different arrays. You can do it by one array.
Moreover, to save images and videos to document directory, you need to write those file to specific path. You will then be able to access them.
#import "ViewController.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import <MediaPlayer/MediaPlayer.h>
#interface ViewController ()
{
NSMutableArray * arr_mediaType;
UIImagePickerController *imagePicker;
UIImage *snap;
NSData *data1;
NSMutableArray * arr_media;
MPMoviePlayerController * moviePlayer;
UIImageView *dot;
}
#end
#implementation ViewController
#synthesize tbl;
- (void)viewDidLoad {
arr_mediaType = [[NSMutableArray alloc]init];
arr_media = [[NSMutableArray alloc]init];
tbl.delegate = self;
tbl.dataSource = self;
[super viewDidLoad];
}
- (IBAction)takePicture:(id)sender {
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
- (IBAction)takeVideo:(id)sender {
NSString *model = [[UIDevice currentDevice] model];
if ([model isEqualToString:#"iPhone Simulator"] || [model isEqualToString:#"iPad Simulator"])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Angry!!!" message:#"No Camera found!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
else
{
imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.videoMaximumDuration = 10;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:imagePicker animated:NO completion:nil];
}
}
-(IBAction)takeAudio
{
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString]; // to get unique name
NSString *soundfile = [NSString stringWithFormat:#"sound%#.m4a",fileName];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:soundfile];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(#"FilePath:%#",soundFileURL);
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
NSError *error = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
error:nil];
_audioRecorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (error)
{
NSLog(#"error: %#", [error localizedDescription]);
} else {
[arr_media addObject:soundFilePath];
[_audioRecorder record];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:#"public.image"]){
[mediaType isEqual: #"Photos"];
[arr_mediaType addObject:#"Photos"];
snap = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"Pic-%#.png", fileName]];
NSData *data = UIImageJPEGRepresentation(snap, 1.0);
[data writeToFile:filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:nil];
//UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//
// NSString *Dir = [paths objectAtIndex:0];
// NSString *fileName = [NSString stringWithFormat:#"Pic-%lf.png", [[NSDate date] timeIntervalSince1970]];
//
// //this path if you want save reference path in sqlite
// NSString *pngPath = [NSString stringWithFormat:#"%#/%#",Dir,fileName];
//
NSLog(#"So finally path is%#",filePath);
[arr_media addObject:filePath];
[tbl reloadData];
}
else {
[mediaType isEqual: #"Videos"];
[arr_mediaType addObject:#"Video"];
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"videoURL --->>> %#",videoURL);
NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:#"video%#.mov", fileName]];
BOOL success = [videoData writeToFile:filePath atomically:NO];
[arr_media addObject:filePath];
NSLog(#"videoURLPath --->>> %#",filePath);
[picker dismissViewControllerAnimated:YES completion:nil];
[tbl reloadData];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arr_mediaType.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cells=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:nil];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cells];
}
cell.textLabel.text = [arr_media objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Photos"]) {
[moviePlayer.view removeFromSuperview];
dot =[[UIImageView alloc] initWithFrame:CGRectMake(40,320,240,128)];
dot.image = [UIImage imageNamed:[arr_media objectAtIndex:indexPath.row]];
[self.view addSubview:dot];
}
else if([[arr_mediaType objectAtIndex:indexPath.row] isEqualToString:#"Videos"])
{
[dot removeFromSuperview];
// NSString*thePath=[[NSBundle mainBundle] pathForResource:[arr_media objectAtIndex:indexPath.row] ofType:#"MOV"];
NSURL*theurl=[NSURL fileURLWithPath:[arr_media objectAtIndex:indexPath.row]];
moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:theurl];
[moviePlayer.view setFrame:CGRectMake(40, 320, 240, 128)];
[moviePlayer prepareToPlay];
[moviePlayer setShouldAutoplay:NO];
[self.view addSubview:moviePlayer.view];
}
else
{
NSString *filePath = [arr_media objectAtIndex:indexPath.row];
NSData *soundData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:filePath]];
player = [[AVAudioPlayer alloc] initWithData:soundData error:nil];
[player setDelegate:self];
[player play];
}
#end
Your issue is that you are not saving the captured images/photos and simply trying to use the paths. Please take a look at Apple Documentation on how to use it. You can save them in your project's Documents directory, save the file name and path as you are doing then use those paths for rendering/playing later on.
As a side note, in your implementation, there are few lines of code that you are executing after [picker dismissViewControllerAnimated:YES completion:nil]. I would advise to utilize completion block here and load your table view once image picker view dismissal is complete. This avoid run time crashes.
EDIT: On OP request
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, #“image1.png”];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
[imageData writeToFile: filePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:^{
// Save your model data and reload table here
}];
}
}

Save image to Documents directory than load it into UIImageView

I have been trying to solve this issue since days. I have an app where the user selects an image than the selected image is saved to the disk and later loaded into a UIImageView, however this does not work, no matter what I try. i have made a small app just to test this, and it does not work there either. The imageView stays blank. Here is my code:
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)button:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.allowsEditing = NO;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *selectedImage = info[UIImagePickerControllerOriginalImage];
[self saveImage:selectedImage];
self.imageView.image = [self loadImage];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)saveImage: (UIImage*)image
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
#"image.png" ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
#"image.png" ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
#end
What am I doing wrong?
You just need to add the delegate of the UIImagePickerController so that following code solve you problem.
- (IBAction)button:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.allowsEditing = NO;
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:nil];
}
Now, In .h file use following code.
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
#property(nonatomic,weak)IBOutlet UIImageView *imageView;
#end

Creating an app's own Photo Gallery (iOS)

Hello I have an application that takes pictures and displays the newly taken pictures to the image view. I can save the image and load it again. It is saved in the app's directory. Is it possible to create a album just for the use of that app? The pictures shouldn't be seen in the iPhone's photo gallery for security purposes. If it is possible, can anyone explain to me how to do it? Here are my current codes.
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
UIImagePickerController *picker;
UIImagePickerController *picker2;
UIImage *image;
IBOutlet UIImageView *imageView;
}
-(IBAction)TakePhoto;
-(IBAction)ChooseExisting;
- (IBAction)btnSave:(id)sender;
- (IBAction)btnLoad:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(IBAction)TakePhoto{
picker = [[UIImagePickerController alloc]init];
picker.delegate=self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker animated:YES completion:NULL];
// [picker release];
}
- (void)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"]; //Add the file name
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
image = [UIImage imageWithData:pngData];
}
-(IBAction)ChooseExisting{
picker2 = [[UIImagePickerController alloc]init];
picker2.delegate=self;
[picker2 setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:picker2 animated:YES completion:NULL];
// [picker release];
}
- (NSString *)documentsPathForFileName:(NSString *)name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
return [documentsPath stringByAppendingPathComponent:name];
}
- (IBAction)btnSave:(id)sender {
NSData *pngData = UIImagePNGRepresentation(image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
}
- (IBAction)btnLoad:(id)sender {
[self loadImage];
[imageView setImage:image];
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
image = [info objectForKey:UIImagePickerControllerOriginalImage];
[imageView setImage:image];
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void)viewDidLoad
{
[self loadImage];
[imageView setImage:image];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end

Resources