カメラロール(ローカルファイル)から写真をピックし、ローカルのURLを指定してStorageにアップロード。その際のDownloadURLをuser.photoURLに指定してやる。
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseStorage
class EditProfileViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var user: User!
var ref: DatabaseReference! //
private var databaseHandle: DatabaseHandle! //
var storage: Storage!
var storageRef: StorageReference!
var localImageURL: NSURL?
@IBAction func uploadImageButtonDidTap(_ sender: Any) {
let ipc = UIImagePickerController()
ipc.delegate = self
self.present(ipc, animated:true, completion:nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion: nil);
self.profileImageView.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
self.localImageURL = info[UIImagePickerController.InfoKey.imageURL] as? NSURL
}
@IBAction func saveDidTap(_ sender: Any) {
let changeRequest = user.createProfileChangeRequest()
guard let imageURL = localImageURL else { return }
let localFile = imageURL as URL // ここは公式ドキュメントに揃えただけなので別に変数化しなくていい
let imageRef = storageRef.child("user/\(user.uid)/images/profile.jpg")
_ = imageRef.putFile(from: localFile, metadata: nil) { metadata, error in
guard let metadata = metadata else {
// Uh-oh, an error occurred!
return
}
// Metadata contains file metadata such as size, content-type.
let size = metadata.size
// You can also access to download URL after upload.
imageRef.downloadURL { (url, error) in
guard let downloadURL = url else {
// Uh-oh, an error occurred!
return
}
changeRequest.photoURL = downloadURL
changeRequest.commitChanges() { (error) in
self.dismiss(animated: true, completion: nil)
}
}
}
}
}
https://firebase.google.com/docs/storage/ios/create-reference?hl=ja
https://firebase.google.com/docs/auth/ios/manage-users?hl=ja#update_a_users_profile
https://stackoverflow.com/questions/40177250/firebase-how-to-get-image-url-from-firebase-storage