簡體   English   中英

解析PFFile錯誤-嘗試獲取圖像文件(Swift2)

[英]Parse PFFile Error - Trying to get an image file (Swift2)

我正在嘗試通過下面的代碼獲取圖像文件。

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

代碼有問題嗎?

@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]);
        }
    }];

希望這對您有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM