2015-12-22 30 views
0

我試圖通過下面的代碼獲取圖像文件。解析PFFile錯誤 - 試圖獲取圖像文件(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 

有什麼不對的代碼?

+0

您實際上沒有從Parse中檢索到'anotherPhoto',所以對象將是空的。這意味着'照片'鍵將是零,但你說'as! PFFile' - as!說「這個價值不會是零」。所以你得到一個異常 – Paulw11

+0

哦!我懂了!但我如何檢索其他照片?使用PFQuery? @ Paulw11 –

+0

是的。查詢或獲取操作 – Paulw11

回答

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

希望這可以幫助你。

+0

謝謝你的朋友! –

+0

不客氣。 :) –