I am unable to save and retrieve image in iOS

2019-08-26 02:11发布

I am unable to save and retrieve image in iOS. I am getting nil image trough this code:

-(NSString *)saveImageDataWithImage:(UIImage *)image
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *photoName = [NSString stringWithFormat:@"%ld.png",
                           (long)[[NSDate date] timeIntervalSince1970]];
    NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:photoName];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:getImagePath])
    {
        NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
        [data1 writeToFile:getImagePath atomically:YES];
    }
    return photoName;
}
-(UIImage *)GetImageFromPath:(NSString *)ImageName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:ImageName];
    UIImage *thumbNail = [[UIImage alloc] initWithContentsOfFile:getImagePath];
    return thumbNail;
}

Why I am getting nil image?

Please help me.

2条回答
2楼-- · 2019-08-26 02:16

Seems like typo in your directory name. Please replace NSDocumentationDirectory with NSDocumentationDirectory and it should work.

查看更多
在下西门庆
3楼-- · 2019-08-26 02:36
-(NSString *)saveImageDataWithImage:(UIImage *)image
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *photoName = [NSString stringWithFormat:@"%ld.png",
                           (long)[[NSDate date] timeIntervalSince1970]];
    NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:photoName];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:getImagePath])
    {
        NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
        [data1 writeToFile:getImagePath atomically:YES];
    }
    return photoName;
}
-(UIImage *)GetImageFromPath:(NSString *)ImageName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:ImageName];
    UIImage *thumbNail = [[UIImage alloc] initWithContentsOfFile:getImagePath];
    return thumbNail;
}
查看更多
登录 后发表回答