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

Asked

Viewed 320 times

0

Hi!

I wonder if Voce can help me, I’m trying to save an image in a sqlite bank, on iphone. But I’m not getting it. Briefly explaining how it works...

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

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

Someone could help!?

1 answer

1


It is even possible to save the image in the bank, but it is not usual. Usually what is done is to save the image in the sandbox of the application (area of the disk that only the app has access to). What you need to save, using a database for example, is the image path.

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 object UIImage on 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];
    }
}
  • Hello! Rafael!! Thanks for the help, I managed to solve this problem by doing almost what you did up there: I received the image from a webservice (when json), and stored it in a Nsstring, then I converted this Nsstring to Nsdata... and then this Nsdata is inserted into the database using the function: sqlite3_bind_blob!! But thanks anyway! And your code is already saved here for future queries!!!

  • Glad you solved it. To help users who come to have the same question, accept the answer or put your solution to the problem. See http://answall.com/help/accepted-answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.