I am unable to save and retrieve image in iOS

拟墨画扇 提交于 2019-12-12 03:38:43

问题


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.


回答1:


-(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;
}



回答2:


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



来源:https://stackoverflow.com/questions/32606971/i-am-unable-to-save-and-retrieve-image-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!