解析PFFile错误 - 尝试获取图像文件(Swift2)

时间:2015-12-22 23:26:32

标签: ios swift parse-platform

我正试图通过此代码获取图像文件。

let anotherPhoto : PFObject = PFObject(className: "Menu")

        let userImageFile = anotherPhoto["photo"] as! PFFile
        userImageFile.getDataInBackgroundWithBlock {
            (imageData: NSData?, error: NSError?) -> Void in
            if error == nil {
                if let imageData = imageData {
                    let image = UIImage(data:imageData)
                }
            }
        }

但总是会发生这个错误

fatal error: unexpectedly found nil while unwrapping an Opcional value

该错误出现在该行

let userImageFile = anotherPhoto["photo"] as! PFFile

代码有问题吗?

1 个答案:

答案 0 :(得分:0)

@paulw是对的。你必须首先从解析中获取你的对象或记录,然后你可以从解析中获取文件(如果有的话)。

您可以按照以下代码(注意:此代码在Objective-C中):

PFQuery *query = [PFQuery queryWithClassName:@"DataTable"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error)
        {
            if ([objects count] > 0 ) {
                PFObject *obj = [(NSArray*)objects objectAtIndex:0];
                PFFile *file = obj[@"FileField"];
                [file getDataInBackgroundWithBlock:^(NSData *Data, NSError *error) {
                    if (!error)
                    {
                        // write the downloaded file to documents dir

                        [Data writeToFile:strlocalFilePath atomically:YES];
                    }
                    else
                    {
                        NSLog(@" error...... %@",error);
                    }
                }];
            }
        }
        else
        {
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];

希望这对你有所帮助。