Hemang
Hemang

Reputation: 27052

iOS : How to upload an image from a URL to Parse?

I'm able to upload an image (in form of PFFile) on parse with their methods available.

NSData *data = ... ;
PFFile *file = [PFFile fileWithData:data];
[file saveInBackground];

Is there a better way to directly upload an image from a url to parse?

Update: The bad way I found is,

To get an image from NSURL to NSData - don't know about the proper way, but this is working. Something like this,

PFFile *file = [PFFile fileWithData:[NSData dataWithContentsOfURL:urlObj]];
[file saveInBackground];

Upvotes: 1

Views: 610

Answers (1)

danh
danh

Reputation: 62676

I think the question is how best to get the data to pass to parse. You're right that dataWithContentsOfUrl is a bad way because it blocks the main thread during the fetch.

Here's a block-based approach to get the data asynchronously:

NSURL *url = [NSURL URLWithString:@"http:// ..."];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (!error) {
        PFFile *file = [PFFile fileWithData:data];
        [file saveInBackground];
    }
}];

Upvotes: 1

Related Questions