Proper way of saving and loading pictures

前端 未结 3 1469
说谎
说谎 2021-02-04 13:41

I am making a small app where the user can create a game profile, input some data and a picture that can be taken with the camera.

I save most of that profile data with

相关标签:
3条回答
  • 2021-02-04 14:27

    I think this("iphone-user-defaults-and-uiimages") post addresses your issue. Don't save blobs to a property list such as NSUserDefaults. In your case I would write to disk directly instead.

    0 讨论(0)
  • 2021-02-04 14:36

    You should save it in Documents or Cache folder. Here is how to do it.

    Saving into Documents folder:

    NSString* path = [NSHomeDirectory() stringByAppendingString:@"/Documents/myImage.png"];
    
    BOOL ok = [[NSFileManager defaultManager] createFileAtPath:path 
              contents:nil attributes:nil];
    
    if (!ok) 
    {
        NSLog(@"Error creating file %@", path);
    } 
    else 
    {
        NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
       [myFileHandle writeData:UIImagePNGRepresentation(yourImage)];
       [myFileHandle closeFile];
    }
    

    Loading from Documents folder:

    NSFileHandle* myFileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
    UIImage* loadedImage = [UIImage imageWithData:[myFileHandle readDataToEndOfFile]];
    

    You can also use UIImageJPEGRepresentation to save your UIImage as a JPEG file. What's more if you want to save it in Cache directory, use:

    [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/"]
    
    0 讨论(0)
  • 2021-02-04 14:41

    One way to do this is use the application's document directory. This is specific to a application and will not be visible to other applications.
    How to create this:
    Just add a static function to App Delegate and use the function where ever the path is required.

    - (NSString )applicationDocumentDirectory {
        /
         Returns the path to the application's documents directory.
         */ 
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
        return basePath;
    }
    
    Hope it Helped..

    0 讨论(0)
提交回复
热议问题