2016-08-24 78 views
0

我試圖將圖像從圖像視圖上傳到Firebase存儲。將UIImage視圖轉換爲NSURL並將其上傳到Firebase

用戶將從相冊或從相機上傳圖像到圖像視圖!我想要的是將圖像從圖像視圖上傳到Firebase存儲。

我試着遵循火力地堡文檔的例子如下:

let localFile: NSURL = ImageView.image 


    let metadata = FIRStorageMetadata() 
    metadata.contentType = "image/jpeg" 

    // Upload file and metadata to the object 'images/mountains.jpg' 
    let uploadTask = storage.child("images/DeviceImage.jpg").putFile(localFile, metadata: metadata); 

    // Listen for state changes, errors, and completion of the upload. 
    uploadTask.observeStatus(.Pause) { snapshot in 
     // Upload paused 
    } 

    uploadTask.observeStatus(.Resume) { snapshot in 
     // Upload resumed, also fires when the upload starts 
    } 

    uploadTask.observeStatus(.Progress) { snapshot in 
     // Upload reported progress 
     if let progress = snapshot.progress { 
      let percentComplete = 100.0 * Double(progress.completedUnitCount)/Double(progress.totalUnitCount) 
     } 
    } 

    uploadTask.observeStatus(.Success) { snapshot in 
     // Upload completed successfully 
    } 

    // Errors only occur in the "Failure" case 
    uploadTask.observeStatus(.Failure) { snapshot in 
     guard let storageError = snapshot.error else { return } 
     guard let errorCode = FIRStorageErrorCode(rawValue: storageError.code) else { return } 
     switch errorCode { 
     case .ObjectNotFound: 
      // File doesn't exist 

     case .Unauthorized: 
      // User doesn't have permission to access file 

     case .Cancelled: 
      // User canceled the upload 

      ... 

     case .Unknown: 
      // Unknown error occurred, inspect the server response 
     } 
    } 

但我不知道如何將UIImageView的轉換成NSURL。

這是我得到的錯誤: enter image description here

+0

首先確保您的硬盤上存在的圖像,然後創建一個NSURL從它的路徑。 – Roecrew

回答

3

你需要將圖像轉換爲磁盤上的文件,並獲得該URL上傳。

let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) 
let filePath = "\(paths[0])/MyImageName.jpg" 

// Save image. 
UIImageJPEGRepresentation(image, 0.90)?.writeToFile(filePath, atomically: true) 

參見:How do I save a UIImage to a file?

一旦寫入磁盤,你可以得到一個URL的文件,像這樣:

let localFile = NSURL(fileURLWithPath: filePath) 
+0

UIImageView上的.image屬性保存對UIImage數據的引用。 let image = myImageView.image –

+0

我會試着讓你知道 – Mariah

+0

對不起,UIImageJPEGRepresentation需要2個參數。我更新了答案。 –