开发者

iPhone UIImage - Data Persistance

Simple question regarding data persistance between application sessions.

My application allows the user to select an image from the Library using a UIImagePickerController. The selected photo is then used as the background to the application.

As the UIImagePickerController delegate method actually returns an image as opposed to an image path, I am wondering what is the best way to persist this image over user sessions?

I do not require any other data to be persisted at the moment, as everything else is pulled in from SQL Server, but I do not want the added overhead of having to store the image in the server as well, which would mean that everytime the user opened the application the background image would first have to be downloaded from the server into a byte array and then converted into an image.

I have found the following code that can save the image:

- (void)saveImage:(UIImage *)image withName:(NSString *)name {
//save image
NSData *data = UIImageJPEGRepresentation(image, 1.0);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,  YES);
NSString *documentsDirectory = [paths o开发者_JS百科bjectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
[fileManager createFileAtPath:fullPath contents:data attributes:nil];

}

I am not on a mac at the moment, so I cannot test this code, but I have a couple of questions regarding the code above:

I don't want a lot of files cluttering the file system. So I would like a single background file (background.png); how would the code above handle a situation where this file already existed?

Would it overwrite the existing file or would it throw an error?

How would I go about loading the image again?


You have to remove the file first:

- (void)saveImage:(UIImage *)image withName:(NSString *)name {
    //save image
    NSData *data = UIImageJPEGRepresentation(image, 1.0);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask,  YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];

    NSError *error = nil;
    if( [fileManager fileExistsAtPath:fullPath] ){
        if( ! [fileManager removeItemAtPath:fullPath error:&error] ) {
            NSLog(@"Failed deleting background image file %@", error);
            // the write below should fail. Add your own flag and check below.
        }
    }
    [data writeToFile:fullPath atomically:YES];
}

Reading back in should work as follows:

...
UIImage *bgImage = [UIImage imageWithContentsOfFile:fullPath];
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜