2016-01-18 76 views
1

我試圖從iOS應用上傳圖像到Parse類。試圖將圖像從iOS上傳到parse.com

的視圖控制器有兩個按鈕和一個ImageView的

按鈕1:從設備的圖片集錦選擇圖片,

ImageView的(myImageView):示出了所選的圖像。

這部分的應用程序工作正常。

在解析,我創建了一個名爲citas_servicio類,有一個叫照片列中,從類型的文件。

按鈕2動作是subirFoto

@IBAction func subirFoto(sender: AnyObject) { 
    if myImageView.image == nil { 
     //image is not included alert user 
     print("Image not uploaded") 
    }else { 
     var posts = PFObject(className: "citas_servicio") 
     posts.saveInBackgroundWithBlock({(success: Bool, error: NSError?) -> Void in 
      if error == nil { 
       /**success saving, Now save image.***/ 

       //create an image data 
       var imageData = UIImagePNGRepresentation(self.myImageView.image!) 
       //create a parse file to store in cloud 
       var parseImageFile = PFFile(name: "uploaded_image.png", data: imageData!) 
       posts["foto"] = parseImageFile 
       posts.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in 
        if error == nil { 
         //take user home 
         print("data uploaded") 
        }else { 
         print(error) 
        } 
       }) 
      }else { 
       print(error) 
      } 
     }) 
    } 
} 

一旦Button2被點擊時,在解析中創建一個新的記錄,但圖像不是在它加入,並打印在控制檯沒有消息。

代碼有什麼問題?

+0

請參閱以下鏈接:http://stackoverflow.com/a/18840159/5247310 –

回答

1

您在保存Object之前設置foto在帖子這就是爲什麼你收到錯誤。首先保存圖像,然後將其設置爲Object

let posts = PFObject(className: "citas_servicio") 
     //create an image data 
     let imageData = UIImagePNGRepresentation(self.myImageView.image!) 
     //create a parse file to store in cloud 
     let parseImageFile = PFFile(name: "uploaded_image.png", data: imageData!) 
     parseImageFile?.saveInBackgroundWithBlock({ (success, error) -> Void in 
      if success{ 
       posts["foto"] = parseImageFile 
       posts.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in 
        if error == nil { 
         //take user home 
         print("data uploaded") 
        }else { 
         print(error) 
        } 
       }) 
      } 
     }) 
+0

謝謝,讓我檢查它... – mvasco

+0

您的代碼有效,謝謝 – mvasco

1

首先保存parseImageFile在成功後,然後將其與PFObject關聯,並保存後臺(PFObject)在background.I希望它會工作。

+0

謝謝,但你可以發佈你的答案與代碼示例? – mvasco

+0

請參閱以下鏈接: - http://stackoverflow.com/questions/18839834/how-to-upload-an-image-to-parse-com-from-uiimageview/18840159#18840159 –

1

你並不需要保存對象,然後用照片再次保存,只需添加到PFObject後創建它。

var posts = PFObject(className: "citas_servicio") 
let imageData = UIImagePNGRepresentation(self.myImageView.image!) 
let parseImageFile = PFFile(name: "uploaded_image.png", data: imageData!) 
posts["foto"] = parseImageFile 

之後,您可以輕鬆地將對象保存在後臺。