Unable to encrypt and decrypt data in plist - ios

I'm trying to encrypt the saved plist data using RNCryptor and decrypt it.
the output is all gibberish in encrypted file but am not able to get the anything after decryption.
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"data.plist"]];
NSError *error1;
bac = [RNEncryptor encryptData:data withSettings:kRNCryptorAES256Settings password:#"abcdef" error:&error1];
NSString *pathToDesktop = [NSString stringWithFormat:#"/Users/rajparmar/Desktop/encrypt.plist"];
[bac writeToFile:pathToDesktop atomically:YES];
Here is the code for decryption
NSError *error1;
NSData *decryptedData = [RNDecryptor decryptData:bac
withPassword:#"abcdef"
error:&error1];
NSString *pathToDesktop1 = [NSString stringWithFormat:#"/Users/rajparmar/Desktop/decrypt.plist"];
[decryptedData writeToFile:pathToDesktop1 atomically:YES];

Complete Example with code using RNEncryptor and RNDecryptor.
#import "ViewController.h"
#import <Security/Security.h>
#import "RNCryptor/RNEncryptor.h"
#import "RNCryptor/RNDecryptor.h"
#interface ViewController () {
UILabel* lable;
NSMutableDictionary* plistDict;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton* btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
btn1.frame = CGRectMake(0, 0, 150, 60);
btn1.backgroundColor = [UIColor lightGrayColor];
[btn1 setTitle:#"SaveData" forState:UIControlStateNormal];
btn1.center = self.view.center;
[btn1 addTarget:self action:#selector(saveDataToPlist:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn1];
UIButton* btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
btn2.frame = CGRectMake(btn1.frame.origin.x, btn1.frame.origin.y + 100, 150, 60);
btn2.backgroundColor = [UIColor lightGrayColor];
[btn2 setTitle:#"Show Data" forState:UIControlStateNormal];
[btn2 addTarget:self action:#selector(getDataFromPlist:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn2];
lable = [[UILabel alloc] initWithFrame:CGRectMake(btn2.frame.origin.x, btn2.frame.origin.y + 100, 300, 40)];
lable.text = #"";
[self.view addSubview:lable];
//create plist if not exits
[self createPlistIfNotExists];
}
#pragma mark - Button Events
- (void)saveDataToPlist:(id)sender
{
NSString* eString = #"Hello World How are you";
[self insertEncryptedDataIntoPlist:eString forKey:#"ENData"];
}
- (void)getDataFromPlist:(id)sender
{
NSString* dString = [self decryptDataFromPlistForKey:#"ENData"];
[lable setText:dString];
}
#pragma mark - Encryption and Decryption
- (void)insertEncryptedDataIntoPlist:(NSString*)aDataString forKey:(NSString*)aKey
{
NSError* error;
NSData* data;
data = [RNEncryptor encryptData:[aDataString dataUsingEncoding:NSUTF8StringEncoding]
withSettings:kRNCryptorAES256Settings
password:#"#ABC123"
error:&error];
if (error) {
NSLog(#"Failed: %#", error);
exit(1);
}
[plistDict setObject:data forKey:aKey];
[plistDict writeToFile:[self getPlistPath] atomically:YES];
}
- (NSString*)decryptDataFromPlistForKey:(NSString*)aKey
{
NSMutableDictionary* savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile:[self getPlistPath]];
NSError* error;
NSData* data;
data = [RNDecryptor decryptData:[[NSData alloc] initWithData:[savedStock valueForKey:aKey]] withPassword:#"#ABC123" error:&error];
if (error) {
NSLog(#"Failed: %#", error);
exit(1);
}
NSString* string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return string;
}
- (void)createPlistIfNotExists
{
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:#"eplist.plist"];
NSFileManager* fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path]) {
path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"eplist.plist"]];
}
if ([fileManager fileExistsAtPath:path]) {
plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
}
else {
// If the file doesn’t exist, create an empty dictionary
plistDict = [[NSMutableDictionary alloc] init];
}
}
- (NSString*)getPlistPath
{
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:#"eplist.plist"];
return path;
}
#end

Related

How to get images for only that data for which images are downloaded from the url

How to get images for only that data for which images are downloaded from the url.Please help for getting this
if(image)
{
CGFloat oX = (([[UIScreen mainScreen]bounds].size.width) -200)/3;
UIImageView *iView = [[UIImageView alloc]initWithFrame:CGRectMake(oX, yValue, 200, height+80)];
[Utility getAndSaveImagesForUrl:str];
[iView setImage:image];
[self.scrollInfo addSubview:iView];
[iView release];
yValue = yValue + height+90;
}
else
{
[Utility getAndSaveImagesForUrl:str];
UILabel * locationLabel = [[UILabel alloc]initWithFrame:CGRectMake(3, yValue, width, height+7)];
[locationLabel setFont:[UIFont boldSystemFontOfSize:15.0f]];
locationLabel.font=[UIFont systemFontOfSize:20.0f];//Kashif
[locationLabel setBackgroundColor:[UIColor clearColor]];
locationLabel.text = info.location;
locationStr = info.location;
[locationLabel setTextColor:[UIColor colorWithRed:66.0/255.0f green:182.0/255.0f blue:241.0/255.0f alpha:1.0]];
[self.scrollInfo addSubview:locationLabel];
[locationLabel release];
yValue = yValue + height+7;
}
As per logically you need to store image as a seperate folder creating in Document directory. like following:
-(NSString*)ImageFolderInDocDirectoryForURL
{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/URL"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
return dataPath;
}
And you can save image in this folder by following code:
NSString *Path = [[self ImageFolderInDocDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:#"Myimage.png"]
[[NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]] writeToFile:Path atomically:YES];
So when you want to get thouse image that downloaded from url just get all image like following code:
-(void)geturlImage{
_items = [NSMutableArray new];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString* FoldePath=[documentsDirectory stringByAppendingPathComponent:#"URL"];//FolderPath
NSError * error;
NSArray * PhotoOFselectedAlbum = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:FoldePath error:&error];
for(NSString* str in PhotoOFselectedAlbum)
{
[_items addObject:[FoldePath stringByAppendingPathComponent:str]];
}
//NSLog(#"image is %#",_items);
}

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

How to load images from documents directory into image view in Objective-C

NSString *path = [NSString stringWithFormat:#"%#/%#",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0], parentFolderName] ;
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
NSEnumerator *enumerator = [dirContents objectEnumerator] ;
id fileName ;
NSMutableArray *fileArray = [[NSMutableArray alloc] init] ;
while (fileName = [enumerator nextObject])
{
NSString *fullFilePath = [path stringByAppendingPathComponent:fileName];
NSRange textRangeJpg = [[fileName lowercaseString] rangeOfString:[#".png" lowercaseString]];
if (textRangeJpg.location != NSNotFound)
{
originalImage = [UIImage imageWithContentsOfFile:fullFilePath];
[fileArray addObject:originalImage];
}
}
You should try this code to save and retrieve image from the document directory:
I have implemented these methods in AppDelegate.m
-(NSString *)getDocumentDirectoryPath:(NSString *)Name
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:Name];
NSLog(#"savedImagePath: %#", savedImagePath);
return savedImagePath;
}
-(BOOL)saveImage:(UIImage *)image withName:(NSString *)Name
{
NSData *imageData = UIImagePNGRepresentation(image);
BOOL success = [imageData writeToFile:[AppDelegate getDocumentDirectoryPath:Name] atomically:NO];
return success;
}
-(UIImage *)getRealtorImage:(NSString *)Name
{
UIImage *img = [UIImage imageWithContentsOfFile:[AppDelegate getDocumentDirectoryPath:Name]];
return img;
}
#Sandy Please try the following code
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100,100,200,200)];
NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:imageFilePath]];
if (imgData != nil)
{
UIImage *thumbNail = [[UIImage alloc] initWithData:imgData];
imageView.image = thumbNail;
}
[self.view addSubView:imageView];

UIScrollView dynamic contents not appearing

I'm having a trouble dynamically adding UIButtons with background image as subviews to a UIScrollView. Its kind of a image gallery using UIButtons on a scrollView. I have used this method for couple of my apps, it works fine for me with the static contents.
But this time, Im loading images from a web service and saved to documents directory, then call the method to create the gallery. Logic is same with my other apps. But I cannot figure out what is the issue here.
I'll put here both the codes one is for retrieving data and other is the creating gallery.
Data retrieving from server
-(void)loadDataFromServer{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
arrCats = [[NSMutableArray alloc]init];
arrPromos = [[NSMutableArray alloc]init];
//[spinMenu startAnimating];
// load promo images from the server
for(int i=0;i<[arrPromos count];i++)
{
NSString *urlString = [Constants getImages:[[arrPromos objectAtIndex:i] objectForKey:#"image"]];
NSLog(#"Get Images API Call : %#", urlString);
NSURL *imageurl = [NSURL URLWithString:urlString];
//get a dispatch queue
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageurl];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
if(imageData != nil){
// save the images temporally
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:[[arrPromos objectAtIndex:i] objectForKey:#"image"]]; //Add the file name
[imageData writeToFile:filePath atomically:YES];
}
});
});
}
// Load promotions from server
dispatch_async(queue, ^{
NSLog(#"Promotions Loading Started");
NSString *urlString = [Constants getAllPromotions:#"GetPromo.php"];
NSLog(#"Get Promotions API Call : %#", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Specify that it will be a GET request
request.HTTPMethod = #"GET";
[request setHTTPShouldHandleCookies:NO];
NSURLResponse *responseURL;
NSError *error;
NSData *dataPromotions = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseURL error:&error];
if (responseURL == nil)
{
// Check for problems
if (error != nil)
{
NSLog(#"Get Promtions Connection failed! Error - %#", [error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Connection Error!" message:#"Promotions data failed to load!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
else
{
NSString *responseString = nil;
responseString = [[NSString alloc] initWithData:dataPromotions encoding:NSUTF8StringEncoding];
if ([responseString rangeOfString:#"error"].location == NSNotFound)
{
NSDictionary *response = [[NSDictionary alloc] init];
response = (NSDictionary *)[responseString JSONValue];
NSLog(#"Response : Promotions %#", response);
if(response != Nil){
if([response count]>0){
arrPromos = [NSMutableArray arrayWithArray:[response objectForKey:#"Promos"]];
NSLog(#"ArrPromos # loading %#", arrPromos);
// create promos galley
[self createPromosGallery];
}
}
}
}
});
Note: [self createPromosGallery]; is calling after download all the images and data.
Create Gallery
-(void) createPromosGallery{
// sort arrPromos based on priority
for(int i=0; i<[arrPromos count];i++){
[arrPromos sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDictionary *dict1 = obj1;
NSDictionary *dict2 = obj2;
NSString *string1;
NSString *string2;
if(![[dict1 objectForKey:#"priority"] isKindOfClass: [NSNull class]])
string1 = [dict1 objectForKey:#"priority"];
if(![[dict2 objectForKey:#"priority"] isKindOfClass: [NSNull class]])
string2 = [dict2 objectForKey:#"priority"];
return [string1 compare:string2 options:NSNumericSearch];
}];
}
NSLog(#"ArrPromos %#", arrPromos);
// scrollView size
CGFloat screenHieght = [UIScreen mainScreen].bounds.size.height;
if(screenHieght>500){
scrollView.frame = CGRectMake(0, 0, 320, 568);
}
else{
scrollView.frame = CGRectMake(0, 0, 320, 480);
}
// define scrollview height
int scrollHieght;
scrollHieght = ([arrPromos count]-1)/2;
NSLog(#"Scroll height %d",scrollHieght);
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width , scrollHieght * 160 +200);
scrollView.pagingEnabled = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.decelerationRate = UIScrollViewDecelerationRateFast;
scrollView.delegate = self;
for(int i=0;i<[arrPromos count];i++)
{
float x;
float y;
if(i%2==0)
{
x=30.0;
y=(i/2)*160+25;
}
if(i%2==1) {
x=170.0;
y=(i/2)*160+25;
}
// retreive saved images
NSString *strImgName;
UIImage *buttonUpImage;
// create buttons
button = [UIButton buttonWithType:UIButtonTypeCustom];
strImgName = [[arrPromos objectAtIndex:i] objectForKey:#"image"];
NSLog(#"Button image name %#", strImgName);
NSArray *sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
NSString *docDirectory = [sysPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#",docDirectory,strImgName];
buttonUpImage = [UIImage imageWithContentsOfFile:filePath];
[button setBackgroundImage:buttonUpImage forState:UIControlStateNormal];
button.frame = CGRectMake(x, y, 120,140);
[button setTag:i];
[button addTarget:self action:#selector(promoBtnPressed:)forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:button];
}
}
Note: I tested on both iOS 7 and 6. In iOS 7, it takes very long time to appear images on scrollView(Currently have only 2 images). Or else, If I TAP on scroolView then the images appear.
In ios 6, nothing appear
//Make a method that has url (fileName) Param
NSArray *documentsDirectory =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];
NSFileManager *fileManager =[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:textPath])
{
return YES;
}
else
{
return NO;
}
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage
imageNamed:#""]];//Placeholder image
if ([url isKindOfClass:[NSString class]])
{
imgView.image = [UIImage imageNamed:[url absoluteString]];
imgView.contentMode = UIViewContentModeScaleAspectFit;
}
else if ([fileManager fileExistsAtPath:url])
{
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];
NSError *error = nil;
NSData *fileData = [NSData dataWithContentsOfFile:textPath options:NSDataReadingMappedIfSafe error:&error];
if (error != nil)
{
DLog(#"There was an error: %#", [error description]);
imgView.image=nil;
}
else
{
imgView.image= [UIImage imageWithData:fileData]
}
}
else
{ UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGPoint center = imgView.center;
// center.x = imgView.bounds.size.width / 2;
spinner.center = center;
[spinner startAnimating];
[imgView addSubview:spinner];
dispatch_queue_t downloadQueue = dispatch_queue_create("iamge downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *imgData = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
[spinner removeFromSuperview];
UIImage *image = [UIImage imageWithData:imgData];
NSError *error = nil;
[imgData writeToFile:url options:NSDataWritingFileProtectionNone error:&error];
if (error != nil)
}
else
{
}
imgView.image = image;
});
});
}
Thats UIImageView loading an image if it doesnot exist in document then it Save it , An Activity indicator is added to show image is loading to save,
Yes it is because you are downloading and then saving the images which takes time. I suggest you to use any library for downloading images and saving them.
Ex : SDWebImage

Store images in application

I've created folder called "Image store" using the following code. my requirment is i want to save images to the folder "Image store" on api success and the images should be saved in application itself not in database or photo album.I want to know the mechanism by which i can store images in application
-(void) createFolder {
UIImage *image = [[UIImage alloc]init];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/ImageStore"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
else
{
}
}
//Make a method that has url (fileName) Param
NSArray *documentsDirectory =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];
NSFileManager *fileManager =[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:textPath])
{
return YES;
}
else
{
return NO;
}
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage
imageNamed:#""]];//Placeholder image
if ([url isKindOfClass:[NSString class]])
{
imgView.image = [UIImage imageNamed:[url absoluteString]];
imgView.contentMode = UIViewContentModeScaleAspectFit;
}
else if ([fileManager fileExistsAtPath:url])
{
NSString *textPath = [documentsDirectory stringByAppendingPathComponent:url];
NSError *error = nil;
NSData *fileData = [NSData dataWithContentsOfFile:textPath options:NSDataReadingMappedIfSafe error:&error];
if (error != nil)
{
DLog(#"There was an error: %#", [error description]);
imgView.image=nil;
}
else
{
imgView.image= [UIImage imageWithData:fileData]
}
}
else
{ UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGPoint center = imgView.center;
// center.x = imgView.bounds.size.width / 2;
spinner.center = center;
[spinner startAnimating];
[imgView addSubview:spinner];
dispatch_queue_t downloadQueue = dispatch_queue_create("iamge downloader", NULL);
dispatch_async(downloadQueue, ^{
NSData *imgData = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
[spinner removeFromSuperview];
UIImage *image = [UIImage imageWithData:imgData];
NSError *error = nil;
[imgData writeToFile:url options:NSDataWritingFileProtectionNone error:&error];
if (error != nil)
{
}
else
{
}
imgView.image = image;
});
});
}
Thats UIImageView loading an image if it doesnot exist in document then it Save it , An Activity indicator is added to show image is loading to save,
u can do something like this
u can run a loop for images like this
//at this point u can get image data
for(int k = 0 ; k < imageCount; k++)
{
[self savePic:[NSString stringWithFormat:#"picName%d",k] withData:imageData];//hear data for each pic u can send
}
- (void)savePic:(NSString *)picName withData:(NSData *)imageData
{
if(imageData != nil)
{
NSString *path = [NSString stringWithFormat:#"/ImageStore/%#.png",pincName];
NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngPath = [NSString stringWithFormat:#"%#%#",Dir,path]; //path means ur destination contain's this format -> "/foldername/picname" pickname must be unique
if(![[NSFileManager defaultManager] fileExistsAtPath:[pngPath stringByDeletingLastPathComponent]])
{
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtPath:[pngPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:&error];
if(error)
{
NSLog(#"error in creating dir");
}
}
[imageData writeToFile:pngPath atomically:YES];
}
}
after successful download and saving u can retrieve images like below
- (UIImage *)checkForImageIn:(NSString *)InDestination
{
NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngPath = [NSString stringWithFormat:#"%#%#",Dir,InDestination];//hear "InDestination" format is like this "/yourFolderName/imagename" as i said imagename must be unique .. :)
UIImage *image = [UIImage imageWithContentsOfFile:pngPath];
if(image)
{
return image;
}
else
return nil;
}
link to find path
see this link to find the path ..
aganin do same this run loop like below
NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
for(int k = 0 ; k < imageCount; k++)
{
UIImage *image = [self checkForImageIn:[NSString stringWithFormat: #"/yourFolderName/ImageName%d",k]];//get the image
[imagesArray addObject:image];//store to use it somewhere ..
}
Write this code after creating directory
NSString *path= [documentsDirectory stringByAppendingPathComponent:#"/ImageStore"];
UIImage *rainyImage =[UImage imageNamed:#"rainy.jpg"];
NSData *Data= UIImageJPEGRepresentation(rainyImage,0.0);
[data writeToFile:path atomically:YES]
The document directory is found like this:
// Let's save the file into Document folder.
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// If you go to the folder below, you will find those pictures
NSLog(#"%#",docDir);
NSLog(#"saving png");
NSString *pngFilePath = [NSString stringWithFormat:#"%#/test.png",docDir];
Thats just a sample of the code provided which tells you where the correct path is to save in your ipone device.
Check the below blog post,it's step by step guide with source code .
Download an Image and Save it as PNG or JPEG in iPhone SDK

Resources