Created
July 16, 2017 16:28
-
-
Save sunnyleeyun/18cae4efa134794a6c8fa91e6c568762 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// cookPic | |
extension SignUpViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { | |
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { | |
var selectedImageFromPicker: UIImage? | |
// 取得從 UIImagePickerController 選擇的檔案 | |
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { | |
selectedImageFromPicker = pickedImage | |
} | |
// 可以自動產生一組獨一無二的 ID 號碼,方便等一下上傳圖片的命名 | |
let uniqueString = NSUUID().uuidString | |
if let user = FIRAuth.auth()?.currentUser { | |
uid = user.uid | |
// 當判斷有 selectedImage 時,我們會在 if 判斷式裡將圖片上傳 | |
if let selectedImage = selectedImageFromPicker { | |
let storageRef = FIRStorage.storage().reference().child("\(uniqueString).png") | |
if let uploadData = UIImagePNGRepresentation(selectedImage) { | |
// 這行就是 FirebaseStorage 關鍵的存取方法。 | |
storageRef.put(uploadData, metadata: nil, completion: { (data, error) in | |
if error != nil { | |
// 若有接收到錯誤,我們就直接印在 Console 就好,在這邊就不另外做處理。 | |
print("Error: \(error!.localizedDescription)") | |
return | |
} | |
// 連結取得方式就是:data?.downloadURL()?.absoluteString。 | |
if let uploadImageUrl = data?.downloadURL()?.absoluteString { | |
// 我們可以 print 出來看看這個連結事不是我們剛剛所上傳的照片。 | |
print("Photo Url: \(uploadImageUrl)") | |
//////////////////////////// cookPic //////////////////////////// | |
let databaseRef = FIRDatabase.database().reference(withPath: "Meal/\(self.uniqueString)").child("cookPic") | |
databaseRef.setValue(uploadImageUrl, withCompletionBlock: { (error, dataRef) in | |
if error != nil { | |
print("Database Error: \(error!.localizedDescription)") | |
} | |
else { | |
print("圖片已儲存") | |
} | |
}) | |
} | |
}) | |
} | |
} | |
dismiss(animated: true, completion: nil) | |
}//uid | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment