2016-08-24 10 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 
     } 
    } 

しかし、私はNSURLにUIImageViewを変換する方法を知りません。あなたは、ディスク上のファイルに画像を変換してアップロードすることのURLを取得する必要があります enter image description here

+0

まず作成し、画像があなたのディスク上に存在することを確認NSURLをそのパスから削除します。 – Roecrew

答えて

3

ここで私が得たエラーです。

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つのパラメータをとります。私は答えを更新しました。 –

関連する問題