Saving image data from json / web-service to sqlite on iphone

0

Hi!

I wonder if you can help me, I'm trying to save an image in an sqlite bank, on the iphone. But I can not.  Briefly explaining how it works ...

The app connects to the server and receives the data using Json. Once received, the data is saved in sqlite, to make the data available to the user when the iphone is offline (no internet connection).

Then I would have to pass the image, coming from Json to a table field in sqlite.

Someone could help!?

    
asked by anonymous 21.07.2014 / 02:10

1 answer

1

You can even save the image to the bank, but it is not usual. Generally what you do is save the image in the sandbox of the application (the disk area to which only the app has access). What you need to save, using a database for example, is the path of the image.

You can download the image as follows:

- (UIImage *)loadImageFromURL:(NSString *)fileURL {

    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    return [UIImage imageWithData:data];
}

So, if you want to save the UIImage object to disk, convert it to NSData :

- (void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {

    NSData *imageData;
    if ([[extension lowercaseString] isEqualToString:@"png"]) {
        imageData = UIImagePNGRepresentation(image);
        extension = @"png";
    } else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"]) {
        imageData = UIImageJPEGRepresentation(image, 1.0);
        extension = @"jpg";
    }

    if (imageData) {
        NSString *imagePath = [directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, extension]];
        [imageData writeToFile:imagePath options:NSAtomicWrite error:nil];
    }
}
    
21.07.2014 / 16:39