Storing images locally on an iOS device

前端 未结 3 1044
别跟我提以往
别跟我提以往 2020-11-28 02:56

Some iOS photo-related apps store images created with the app somewhere other than the photo library. For example Fat Booth shows a scrolling list of photos created with the

3条回答
  •  佛祖请我去吃肉
    2020-11-28 03:37

    The simplest way is to save it in the app's Documents directory and save the path with NSUserDefaults like so:

    NSData *imageData = UIImagePNGRepresentation(newImage);
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",@"cached"]];
    
    NSLog(@"pre writing to file");
    if (![imageData writeToFile:imagePath atomically:NO]) 
    {
        NSLog(@"Failed to cache image data to disk");
    }
    else
    {
        NSLog(@"the cachedImagedPath is %@",imagePath); 
    }
    

    Then save the imagePath in some dictionary in NSUserDefaults or however you'd like, and then to retrieve it just do:

     NSString *theImagePath = [yourDictionary objectForKey:@"cachedImagePath"];
     UIImage *customImage = [UIImage imageWithContentsOfFile:theImagePath];
    

提交回复
热议问题