How to upload an image to Parse.com from UIImageVi

2019-01-23 10:24发布

问题:

My App is called "Draw Me" and use Parse.com. User draws an image in UIImageView and it should be saved(uploaded) to Parse.com. Can someone advise how to do it?

回答1:

Parse has an iOS tutorial on this exact topic: https://parse.com/tutorials/anypic

Christian has outlined how to save the image itself, but I assume you also want to associate it with a PFObject as well. Building on his answer (with an example of saving out as jpeg)

// Convert to JPEG with 50% quality
NSData* data = UIImageJPEGRepresentation(imageView.image, 0.5f);
PFFile *imageFile = [PFFile fileWithName:@"Image.jpg" data:data];

// Save the image to Parse

[imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
    if (!error) {
        // The image has now been uploaded to Parse. Associate it with a new object 
        PFObject* newPhotoObject = [PFObject objectWithClassName:@"PhotoObject"];
        [newPhotoObject setObject:imageFile forKey:@"image"];

        [newPhotoObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (!error) {
                NSLog(@"Saved");
            }
            else{
                // Error
                NSLog(@"Error: %@ %@", error, [error userInfo]);
            }
        }];
    }
}];


回答2:

Here's how to go about doing this:

UIImageView *imageView; // ...image view from previous code
NSData *imageData = UIImagePNGRepresentation(imageView.image);
PFFile *file = [PFFile fileWithData:imageData]
[file saveInBackground];

…and to retrieve it again:

[file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
  if (!error) {
    imageView.image = [UIImage imageWithData:data];
  }
}];