views:

75

answers:

1

Hi all, I want to save the loaded image from server in idle time.I use the following to to save image in iPhone memory.

- (void)saveImage:(UIImage *)image withName:(NSString *)name
{  

    NSData *data1 = UIImageJPEGRepresentation(image, 1.0);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
    [fileManager createFileAtPath:fullPath contents:data1 attributes:nil];

    if (image==nil) {
        NSLog(@"Not Saved...:%@",name);
    }


}

but when his method called i got halt time....i don't want that...i want to save image when iPhone is inactive.....can help??

Thanks

+1  A: 

You need to do this in the background, using a thread.

If you're supporting iOS 4.0 only, it's really easy:

- (void)saveImage:(UIImage *)image withName:(NSString *)name {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL), ^{
        NSData *data1 = UIImageJPEGRepresentation(image, 1.0);
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
        [fileManager createFileAtPath:fullPath contents:data1 attributes:nil];

        if (image==nil) {
            NSLog(@"Not Saved...:%@",name);
        }
    });
}

Otherwise, look up the NSThread documentation, or performSelectorInBackground:withObject:.

jtbandes
Hi,i am using iOS 4.....but..i got error in your code...does it syntactically right??
Rony
Whoops, forgot a {...
jtbandes
i think so....thanks:)
Rony