download and save image to root - iphone

How would i download and save an image to the root of the application so basically i can access the image via
[UIImage imageNamed:#"myimage.jpg"];
Thanks
Mason

First you need to get the Image Data
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://media03.linkedin.com/mpr/mpr/shrink_80_80/p/3/000/064/2e2/1bd3849.jpg"]];
Then you need to write the data to Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathLD = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"imageLD%d.jpeg",[[NSDate date] timeIntervalSince1970]]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: pathLD]){
[imageData writeToFile:pathLD atomically:YES];
} else {
NSLog(#"File exists at path:%#", pathLD);
}
To get the image from Documents you do:
[UIImage imageWithContentsOfFile:pathLD];
Good luck :D;

You shouldn't for various reasons. Consider your application directory as being read-only.
You should use the Documents or Library directory. Apple recommends that you should use the Documents directory if your files should be user-accessible via iTunes (if you have enabled the file sharing via iTunes), or use a custom subdirectory of Library (which you need to create with NSFileManager) if it shouldn't be user-visible (but should be backed up).
You can query the path to the Library directory like this:
NSArray *paths;
paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
NSUserDomainMask, YES);
// dir = [paths objectAtIndex:0];
Substitute NSLibraryDirectory with NSDocumentsDirectory to get the Documents directory.
Then you would make a method that returns the full path to your image, and you would then do:
[UIImage imageWithContentsOfFile:[self pathForImage:#"myimage.jpg"]]

Related

what is the best way to store bulk of images and MP3 song iOS Sdk

i am doing one iphone app, for that i have to store bulk of MP3 song and images.
can ay one tell me what is the best to store those in terms of performance.
Store the image and songs 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/songs - 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;
}
store the MP3 song and images into resources folder of your app project and give the refrences in the sqlite database(because saving large files in sqlite database is not a good practice)
I would suggest you to store all items of large size on the device disk, i.e, Documents directory and store their physical path in core data or sqlite or at least in a plist file so that you can retrieve them as per your convenience.

How can I save a file into appbundle

I have an image named my-image. Can I save this image to the application bundle? If yes, can you provide me the code or paths.
As of now, I have the following code –
NSData * imageData = UIImagePNGRepresentation(userSavedImage); //convert image into .png format.
NSFileManager * fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString * documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString * fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",txtImageName.text]]; //add our image to the path
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the image
NSLog(#"image saved");
However it is saving in
/Users/tsplmac01/Library/Application Support/iPhone Simulator/4.3/Applications/BC5DE1D8-B875-44BC-AC74-04A17329F29A/.
& not in the application bundle. Please tell me how I can do it.
The app bundle is read only for the app, so it is not possible to write to it.
This is a good restriction, because it would otherwise be wiped out when the app gets updated. You may want to write to the documents directory instead.

Check if file name exists in document directory

In my application I am using the following code to save images/files into the application’s document directory:
-(void)saveImageDetailsToAppBundle{
NSData *imageData = UIImagePNGRepresentation(userSavedImage); //convert image into .png format.
NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",txtImageName.text]]; //add our image to the path
NSLog(fullPath);
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the image
NSLog(#"image saved");
}
However, there is a problem with the image name. If a file exists in the documents directory, the new file with the same name will overwrite the old file. How can I check if the file name exists in the documents directory?
Use NSFileManager's fileExistsAtPath: method to check if it exists or not.
usage
if ( ![fileManager fileExistsAtPath:filePath] ) {
/* File doesn't exist. Save the image at the path */
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
} else {
/* File exists at path. Resolve and save */
}
if ([[NSFileManager defaultManager] fileExistsAtPath:myFilePath])
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:#"file name"];
if([fileManager fileExistsAtPath:writablePath]){
// file exist
}
else{
// file doesn't exist
}
As Apple Documentation says it is better to perform some action and then handle no file existance than checking if file is existing.
Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions and Secure File Operations” in Secure Coding Guide.

Application's Document folder in iphone

I am using dropbox API and downloading file in application document folder.
I am able to view list of files in table from document directory. How can I read photos or file from this table view?
And what about the iPhone. Can we access document folder directly?
This is the more commonly used approach to get the documents directory –
NSArray *searchResults = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [searchResults objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
You can use NSFileManager to examine the contents of the directory. You can look at the contentsOfDirectoryAtPath:error: method.
Access document Folder -
NSDictionary *theCatalogInfo=nil;
NSString *theCatalogFilePath = [NSString stringWithFormat:#"%#/Documents/",NSHomeDirectory()];
theCatalogFilePath = [theCatalogFilePath stringByAppendingString:#"File Name"];
if(nil!=theCatalogFilePath)
{
theCatalogInfo=[[NSDictionary alloc]initWithContentsOfFile:theCatalogFilePath];
}
return theCatalogInfo;

Multiple Application Support Directories for iPhone Simulator?

I am developing an iPhone app with someone else. The app works fine for me, but he is running into a bug. We think this bug is related to the fact that he is getting multiple Application directories for this same app. In my ~/Library/Application Support/iPhone Simulator/User/Applications, I only have one folder at all times.
He says that he will get 3 or 4 directories when he is only working on this one app. We think this is our problem because our bug has to do with displaying images that are stored in the app's Documents folder. Does anyone know why he is ending up with multiple directories or how to stop it?
Edit:
Here is the code for writing the image to a file:
NSData *image = [NSData dataWithContentsOfURL:[NSURL URLWithString:[currentArticle articleImage]]];
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *imagePath = [array objectAtIndex:0];
NSFileManager *NSFM = [NSFileManager defaultManager];
BOOL isDir = YES;
if(![NSFM fileExistsAtPath:imagePath isDirectory:&isDir])
if(![NSFM createDirectoryAtPath:imagePath attributes:nil])
NSLog(#"error");
imagePath = [imagePath stringByAppendingFormat:#"/images"];
if(![NSFM fileExistsAtPath:imagePath isDirectory:&isDir])
if(![NSFM createDirectoryAtPath:imagePath attributes:nil])
NSLog(#"error");
imagePath = [imagePath stringByAppendingFormat:#"/%#.jpg", [currentArticle uniqueID]];
[image writeToFile:imagePath atomically:NO];
And here is the code for getting the path when I need the image:
- (NSString *)imagePath
{
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *imagePath = [array objectAtIndex:0];
return [imagePath stringByAppendingFormat:#"/images/%#.jpg", [self uniqueID]];
}
The app works great for me, but my partner says that the images don't show up intermittently, and he notices that he gets multiple directories in his Applications folder.
I had this problem (I was saving photos in the apps documents directory) and after every new build the directory get's renamed, so my paths were no longer valid. I cooked up these 2 functions (in my app delegate) that will give me a path for the file I want to save or load from the documents or temp directory. Even if the app directory changes, as long as you only store the file name and not the full path, and then use your helper functions to get the path when you need it later you will be ok. Here's my functions for this:
+ (NSString*)fullPathToFile:(NSString*)file {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:file];
}
+ (NSString*)fullPathToTemporaryFile:(NSString*)file {
return [NSTemporaryDirectory() stringByAppendingPathComponent:file];
}
Works like a charm.