swift:从照片库中获取图像并上传到firebase

时间:2016-11-30 00:37:04

标签: swift3 ios10 firebase-storage

到目前为止,我找不到任何对我有用的东西..我正在尝试将我在照片库中的内容(最近拍摄的照片保存在库中)并上传到Firebase存储。

以下代码是保存图像并将其添加到库中:

// MARK: - Save image

@IBAction func savePhoto(_ sender: Any) {
    UIImageWriteToSavedPhotosAlbum(licensePhoto.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}


//MARK: - Add image to Library

func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        // we got back an error!
        let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    } else {
        let alert = UIAlertController(title: "Saved!", message: "Image saved successfully", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
}

任何帮助将不胜感激。

我试过以下代码,只是给我一个错误: 致命错误:注册后解包可选值时意外发现nil!:

    // . . .  upload license photo to firebase


    var data = NSData()
    data = UIImageJPEGRepresentation(licensePhoto.image!, 0.8)! as NSData
    // set upload path
    let filePath = "\(FIRAuth.auth()!.currentUser!.uid)/\("userPhoto")"
    let metaData = FIRStorageMetadata()
    metaData.contentType = "image/jpg"
    DataService.Instance.storageRef.child(filePath).put(data as Data, metadata: metaData){(metaData,error) in
        if let error = error {
            print(error.localizedDescription)
            return
        }else{
            //store downloadURL
            let downloadURL = metaData!.downloadURL()!.absoluteString
            //store downloadURL at database
            DataService.Instance.dbRef.child("users").child(FIRAuth.auth()!.currentUser!.uid).updateChildValues(["userPhoto": downloadURL])
        }

    }
}

1 个答案:

答案 0 :(得分:0)

我找到了答案:

  // . . .  upload license photo to firebase

    let storage = FIRStorage.storage().reference()
    let tempImgRef = storage.child("tmpDir/tmpImage.jpg")

    var data: NSData = NSData()
    data = UIImageJPEGRepresentation(licensePhoto.image!, 0.8)! as NSData

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

    tempImgRef.put(data as Data, metadata: metaData, completion: { (metaData, error) in
        if error == nil {
            print("success")

        } else {
            print(error?.localizedDescription as Any)
        }
    })
}