Should I store the multiple image files as NSData to SQLite or
save physical files to Document Folder??
Thanks
Store the image in the application directory. This is best and easy way to handle. Try the following code. it will be help you.
/Store Image/Songs files to Application Directory
+(BOOL)writeToFile:(NSData *)data fileName:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
return [data writeToFile:appFile atomically:YES];
}
//Image - Retrieve from Application Directory
+(NSData *)readFromFile:(NSString *)fileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
if (myData) {
return myData;
}
return nil;
}
Related
I have a graphical application with some predefined tool configurations. At the first lunch of the application I would like to copy these default configuration files into ~/Library/Containers//Data/Library/... from the inside of the bundle. How to do that?
Try this it'll help you.
-(void)copy
{
NSFileManager *filemanager = [NSFileManager defaultManager];
NSError *error;
NSString *path = [self getPath];
BOOL sucess = [filemanager fileExistsAtPath:path];
if(!sucess){
NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"/*put your assets name with extension here */"];
sucess = [filemanager copyItemAtPath:defaultPath toPath:path error:&error];
if (!sucess) {
NSAssert1(0, #"Failed '%#'.", [error localizedDescription]);
}
}
}
-(NSString *) getPath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"/*put your assets name with extension here */"];
}
Im trying to save and load an image picked from camera roll within my app. I get an error when I press either the load or save button
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView CGImage]: unrecognized selector sent to instance 0xe637640'
any thoughts?
AppDelagate .m
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory i nDomains:NSUserDomainMask] lastObject];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
.m of class im trying to save/load image
- (IBAction)save:(id)sender {
UIImage *myImage = imageView;
NSData *data = UIImagePNGRepresentation(myImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *appDocsDirectory = [paths objectAtIndex:0];
}
- (IBAction)load:(id)sender {
UIImage *myImage = imageView;
NSData *data = UIImagePNGRepresentation(myImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *appDocsDirectory = [paths objectAtIndex:0];
UIImage* thumImage = [UIImage imageWithContentsOfFile: [NSString stringWithFormat:#"%#/%#.png", appDocsDirectory, #"myNewFile"]];
}
this error means that message CGImage is sent to object of type UIImageView, but UIImageView does not response to it. The problem is seemed to be in
UIImage *myImage = imageView;
You do not write properly implementation of imageView, so I can not say exactly, but I assume that imageView is UIImageView, which is subclass of UIView, and you are assigning it to UIImage. Try
UIImage *myImage = [imageView image];
instead. I think that should works))
by the way, why do you need first and second strings of code in -load? They are unnecessary:
- (IBAction)load:(id)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *appDocsDirectory = [paths objectAtIndex:0];
UIImage* thumImage = [UIImage imageWithContentsOfFile: [NSString stringWithFormat:#"%#/%#.png", appDocsDirectory, #"myNewFile"]];
}
I've been trying to write data back to a pre-defined plist file (data.plist) in my bundle. Using the code below I call the routine 'dictionaryFromPlist' to open the file and then call 'writeDictionaryToPlist' to write to the plist file. However, no data gets added to the plist file.
NSDictionary *dict = [self dictionaryFromPlist];
NSString *key = #"Reports";
NSString *value = #"TestingTesting";
[dict setValue:value forKey:key];
[self writeDictionaryToPlist:dict];
- (NSMutableDictionary*)dictionaryFromPlist {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"plist"];
NSMutableDictionary* propertyListValues = [[NSMutableDictionary alloc]
initWithContentsOfFile:filePath];
return [propertyListValues autorelease];
}
- (BOOL)writeDictionaryToPlist:(NSDictionary*)plistDict{
NSString *filePath = #"data.plist";
BOOL result = [plistDict writeToFile:filePath atomically:YES];
return result;
}
The code runs through successfully and no error is thrown but no data is added to my plist file.
You can not write to your bundle, it is read only. If your case though, you are writing to a relative path, not to the bundle.
I'm not sure what the default working directory is for iOS apps. It is best to use absolute paths. You should be writing to the documents/cache directory. Something like this will get the path for you:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
Then just grab the lastObject and prepend that to your file name.
As mentioned by #logancautrell you can not write in mainbundle, you can save your plist in the app documents folder, you could do so:
NSString *path = #"example.plist";
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count]> 0)? [paths objectAtIndex: 0]: nil;
NSString *documentPath = [basePath stringByAppendingPathComponent:path] // Documents
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL checkfile = [fileManager fileExistsAtPath: documentPath];
NSLog(#"%#", (checkFile ? #"Exist": #"Not exist"));//check if exist
if(!checkfile) {//if not exist
BOOL copyFileToDoc = [yourDictionary writeToFile:documentPath atomically: YES];
NSLog(#"%#",(copyFileToDoc ? #"Copied": #"Not copied"));
}
I'm making an app where I need to copy certain file from the app bundle to the user's Application Support folder. This is the code I'm using actually:
NSBundle *thisBundle = [NSBundle mainBundle];
NSString *executableName = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleExecutable"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *userpath = [paths objectAtIndex:0];
userpath = [userpath stringByAppendingPathComponent:executableName]; // The file will go in this directory
NSString *saveFilePath = [userpath stringByAppendingPathComponent:#"db.sqlite"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
[fileManager copyItemAtPath:[thisBundle pathForResource:#"db" ofType:#"sqlite"] toPath:saveFilePath error:NULL];
But this doesn't copies anything, BTW this is a Mac app.
Finally got it working with adding
if ([fileManager fileExistsAtPath:userpath] == NO)
[fileManager createDirectoryAtPath:userpath withIntermediateDirectories:YES attributes:nil error:nil];
And the resulting code is:
NSBundle *thisBundle = [NSBundle mainBundle];
NSString *executableName = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleExecutable"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *userpath = [paths objectAtIndex:0];
userpath = [userpath stringByAppendingPathComponent:executableName]; // The file will go in this directory
NSString *saveFilePath = [userpath stringByAppendingPathComponent:#"db.sqlite"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:userpath] == NO)
[fileManager createDirectoryAtPath:userpath withIntermediateDirectories:YES attributes:nil error:nil];
[fileManager copyItemAtPath:[thisBundle pathForResource:#"db" ofType:#"sqlite"] toPath:saveFilePath error:NULL];
You might want to double-check your file paths:
NSLog(#"src: %#", [thisBundle pathForResource:#"db" ofType:#"sqlite"]);
NSLog(#"dst: %#", saveFilePath);
I would like to know if it's possible to play a video from an NSData object... with the MPMoviePlayerController.
Ben's answer works perfectly on simulator but wont work on the device, You cannot write anywhere on the device. Check code below
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"myMove.mp4"];
[videoData writeToFile:path atomically:YES];
NSURL *moveUrl = [NSURL fileURLWithPath:path];
player = [[MPMoviePlayerController alloc]init];
[player setContentURL:moveUrl];
player.view.frame = viewPlayer.bounds;
[viewPlayer addSubview:player.view];
[player play];
As far as I know this is not possible. If the data comes from your DB, can you save it into a temporary file and play that?
It is better to use NSFileManager in this case instead writeToFile
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"myMove.mp4"];
[[NSFileManager defaultManager] createFileAtPath:path contents:videoData attributes:nil];
NSURL *moveUrl = [NSURL fileURLWithPath:path];
player = [[MPMoviePlayerController alloc]init];
[player setContentURL:moveUrl];
player.view.frame = viewPlayer.bounds;
[viewPlayer addSubview:player.view];
[player play];
create a file with the type of your NSData for example if your NSData is type of mp4 create a file with that type - for example - "myMove.mp4"
copy past the file to your app resurces
add this code
NSData *mediaData; //your data
NSString *movePath=[[NSBundle mainBundle] pathForResource:#"myMove" ofType:#"mp4"];
[mediaData writeToFile:movePath atomically:YES];
NSURL *moveUrl= [NSURL fileURLWithPath:movePath];
MPMoviePlayerController *movePlayer=[[MPMoviePlayerController alloc]init];
[movePlayer setContentURL:moveUrl];
[movePlayer play];