Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save file in resource folder of an app in Objective-c

i'm developing an app in objective-c for iphone. My problem is that my application must save an image taken from a url. The folder is read only i think.. This is my code to save image:

-(void)banner:(NSString *)path{
    NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
    UIImage *image = [UIImage imageWithData: imageData];
    NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
    NSString* pathEnd =  [resourcePath stringByAppendingFormat:@"/banner.png"];
    NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
    NSError *writeError = nil;
    [data1 writeToFile:pathEnd options:NSDataWritingAtomic error:&writeError];
}

but when i retrieve image, it isn't in that folder. what can i do?

like image 405
Jayyrus Avatar asked Nov 14 '11 14:11

Jayyrus


1 Answers

You can't, the application bundle is readonly. You should save any data in either the document or cache directory.

-(void)banner:(NSString *)path{
    NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
    UIImage *image = [UIImage imageWithData: imageData];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"banner.png"];

    NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
    NSError *writeError = nil;

   [data1 writeToFile:filePath options:NSDataWritingAtomic error:&writeError];

   if (writeError) {
      NSLog(@"Error writing file: %@", writeError);
   }
}

Is there any reason to convert the data an image first and back to an NSData object again?

If not you could just do this:

-(void)banner:(NSString *)path{
   NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);         NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"banner.png"];       
   NSError *writeError = nil;
   [imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];

   if (writeError) {
      NSLog(@"Error writing file: %@", writeError);
   }
}
like image 73
rckoenes Avatar answered Oct 24 '22 03:10

rckoenes