Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- import FirebaseStorage
- class UploadDataViewController: UIViewController {
- let imageName = "/profile.jpg"
- var imageFileURL: URL?
- var storageRef: StorageReference! = nil
- typealias CompletionHandler = (_ success: Bool,_ metadata: StorageMetadata?,_ downloadUrl: URL?) -> Void
- override func viewDidLoad() {
- super.viewDidLoad()
- self.storageRef = Storage.storage().reference()
- self.saveUserProfile()
- }
- func saveUserProfile() {
- let image = UIImage(named: "profile")
- if createImgUrl(image: image!) {
- self.uploadImageWithUrl(fileUrl: self.imageFileURL!, fileName: "userID1") { (success, metadata, downloadUrl) in
- if success {
- // Can save this download url into your database for further use/download
- print("Image uploaded successfully and downloading url is \(downloadUrl)")
- } else {
- print("Error while uploading image")
- }
- }
- } else {
- print("Error while creating document url for this image")
- }
- }
- // save your image to document directory
- func createImgUrl(image:UIImage) -> Bool {
- let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
- self.imageFileURL = documentsDirectory.appendingPathComponent(self.imageName)
- if let data = UIImageJPEGRepresentation(image, 0.5) {
- do {
- try data.write(to: self.imageFileURL!)
- return true
- } catch {
- print("error saving file:", error)
- }
- }
- return false
- }
- // Upload an image file to Firebase - (Google cloud storage bucket)
- func uploadImageWithUrl(fileUrl:URL, fileName:String, completionHandler: @escaping CompletionHandler) {
- let imagesRef = storageRef.child("user_profile")
- let fileRef = imagesRef.child(fileName).child(self.imageName)
- let imgMetadata = StorageMetadata()
- imgMetadata.contentType = "image/jpeg"
- let uploadTask = fileRef.putFile(from: fileUrl, metadata: imgMetadata) { metadata, error in
- guard let metadata = metadata else {
- return completionHandler(false, nil, nil)
- }
- fileRef.downloadURL { (url, error) in
- guard let downloadURL = url else {
- return completionHandler(false, nil, nil)
- }
- print("Downloaded Url for uploaded image is: \(downloadURL)")
- completionHandler(true, metadata, downloadURL)
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement