从Parse iOS下载图像

时间:2014-05-09 15:11:22

标签: ios objective-c parse-platform

我正在编写一个允许用户在Parse上获取和存储图像的应用程序。到目前为止,我已经设法通过使用以下逻辑将图像数组保存到Parse:

  • 拍摄图片
  • 将对象添加到数组
  • 将数组转换为NSData
  • 将NSData转换为PFFile
  • 设置文件上传目的地(通过唯一的objectId)
  • 将PFFile上传到Parse

这就是代码的样子;请原谅,它现在在dismissViewController中,我只是想让它成功保存:

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
_takenImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
[self dismissViewControllerAnimated:YES completion:^
{
    // Add object to array: Working
    [_tankImagesArray addObject:_takenImage];
    NSLog(@"Number of images taken: %lu", (unsigned long)_tankImagesArray.count);

    // Convert array to NSData Object
    NSData *imageData = [NSKeyedArchiver archivedDataWithRootObject:_tankImagesArray];

    // Convert NSData Object to PFFile
    PFFile *imageFile = [PFFile fileWithData:imageData];

    PFQuery *tankQuery = [PFQuery queryWithClassName:@"SavedTanks"];
    _tankObject = [tankQuery getObjectWithId:_passedValue];

    [_tankObject setObject:imageFile forKey:@"tankImages"];

    [_tankObject save];
}];
}

现在,我的问题是:我究竟如何检索该文件?我的最终目标是允许用户查看他们过去拍摄的图像并添加到集合中的图片列表并将其上传到服务器。我只是不确定如何在上传文件后检索文件,并确保维护完整性。

5 个答案:

答案 0 :(得分:3)

你有没有尝试过:

PFQuery *query = [PFQuery queryWithClassName:@"SavedTanks"];
[query whereKey:@"tankImages" equalTo:@"your_image.jpg"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  if (!error) {
    // The find succeeded.
    NSLog(@"Successfully retrieved %d images.", objects.count);
    // Do something with the found objects
    for (PFObject *object in objects) {
        NSLog(@"%@", object.objectId);
    }
  } else {
    // Log details of the failure
    NSLog(@"Error: %@ %@", error, [error userInfo]);
  }
}];

答案 1 :(得分:3)

PFQuery *query = [PFQuery queryWithClassName:@"SavedTanks"];
// Add constraints here to get the image you want (like the objectId or something else)
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
  if (!error) {    
    for (PFObject *object in objects) {
        PFFile *imageFile = object[@"tankImages"];
        [imageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
            if (!error) {
                UIImage *image = [UIImage imageWithData:imageData];  // Here is your image. Put it in a UIImageView or whatever
            }
        }];        
    }
  } else {
    // Log details of the failure
  }
}];

答案 2 :(得分:1)

在您的收藏夹视图的.h文件中,您需要具有以下内容。请注意,我构建的那个可以像一个图像,然后使用分段控制器对喜欢的图像进行排序。

#import <UIKit/UIKit.h>
#import "UICollectionCell.h"
#import <Parse/Parse.h>

@interface ParseViewController : UIViewController {

    NSArray *imageFilesArray;
    NSMutableArray *imagesArray;
}

@property (weak, nonatomic) IBOutlet UICollectionView *imagesCollection;
- (IBAction)segmentSelected:(id)sender;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentedController;



@end

然后在您的集合视图的.m文件中

    @interface ParseViewController ()

@end

@implementation ParseViewController

@synthesize imagesCollection;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self queryParseMethod];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// code to add the number of images etc as per table view

-(void) queryParseMethod {
    NSLog(@"start query");
    PFQuery *query = [PFQuery queryWithClassName:@"collectionView"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            imageFilesArray = [[NSArray alloc] initWithArray:objects];
            NSLog(@"%@", imageFilesArray);
            [imagesCollection reloadData];
        }
    }];

}

#pragma mark - UICollectionView data source

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    // number of sections
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    // number of items
    return [imageFilesArray count];

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // the custom cell we named for the reusable identifier
    static NSString *cellIdentifier = @"imageCell";
    UICollectionCell *cell = (UICollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    PFObject *imageObject = [imageFilesArray objectAtIndex:indexPath.row];
    PFFile *imageFile = [imageObject objectForKey:@"imageFile"];

    // show loading spinner
    [cell.loadingSpinner startAnimating];
    cell.loadingSpinner.hidden = NO;

    [imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
        if (!error) {
            NSLog(@"%@", data);
            cell.parseImage.image = [UIImage imageWithData:data];
            [cell.loadingSpinner stopAnimating];
            cell.loadingSpinner.hidden = YES;

        }
    }];

    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self likeImage:[imageFilesArray objectAtIndex:indexPath.row]];
}

-(void) likeImage:(PFObject *)object {

    [object addUniqueObject:[PFUser currentUser].objectId forKey:@"favorites"];

    [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (!error) {
            NSLog(@"liked picture!");
            [self likedSuccess];
        }
        else {
            [self likedFail];
        }
    }];
}

-(void) likedSuccess {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"You have succesfully liked the image" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}

-(void) likedFail {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Unsuccesfull" message:@"You have been unable to like the image" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)segmentSelected:(id)sender {
    if (_segmentedController.selectedSegmentIndex == 0) {
        [self queryParseMethod];
    }
    if (_segmentedController.selectedSegmentIndex == 1) {
        [self retrieveLikedImages];
    }
}

-(void) retrieveLikedImages {
    PFQuery *getFavorites = [PFQuery queryWithClassName:@"collectionView"];
    [getFavorites whereKey:@"favorites" equalTo:[PFUser currentUser].objectId];

    [getFavorites findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            imageFilesArray = [[NSArray alloc] initWithArray:objects];
            [imagesCollection reloadData];
        }
    }];
}



@end

希望这对你有所帮助。

答案 3 :(得分:0)

所有上述解决方案都是正确的,但是想要添加另一种方式来支持SDWebImage的图像缓存或任何类似的库。 成功完成后,您将拥有PFFile,其财产&#34; url&#34;将返回保存它的图像的精确URL。您可以使用它来加载图像。使用这种方法,我能够将基于密钥的图像缓存作为URL。

...
NSString *strUrl = pfFileObject.url;
...
...
[img sd_setImageWithURL:[NSURL URLWithString:strUrl]];

答案 4 :(得分:0)

为什么要从用户已经在本地拥有它们的解析下载照片?

我建议您使用:https://github.com/AFNetworking/AFNetworking

您还可以将本地照片保存到缓存中,以便您轻松访问它们,这样您就不需要从解析中下载...

现在如果您仍然想要从解析中下载照片,只需进行正常查询并下载所有照片解析对象,您就会在PFObject中获得照片的PFFile。

示例:

PFQuery *query = [PFQuery queryWithClassName:@"SavedTanks"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        for(PFObject *obj in objects){
            PFFile *file = [obj objectForKey:@"tankImages"];

            // now you can use this url to download the photo with AFNetwork
            NSLog(@"%@",file.url);
        }
    }
}];