简体   繁体   中英

Swift4 : Download photo from Firebase

I want to download a photo that was previously uploaded from Firebase. I am using the following code:

    fbUser = Auth.auth().currentUser
    let storage = Storage.storage()
    let storageRef = storage.reference(forURL: "somepath.some")
    let profilePicRef = storageRef.child(fbUser.uid+"_profile_pic.jpg")

    var imageFB : UIImage? = nil

    profilePicRef.downloadURL(completion: { (url, error) in

        if error != nil {
            print(error!)
            return
        }

        URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

            if error != nil {
                print(error!)
                return
            }

            guard let imageData = UIImage(data: data!) else { return }

            DispatchQueue.main.async {
                imageFB = imageData
            }

        }).resume()

    })

The photo is there - if I delete the photo, then I get an error that the file is missing. However, after the download, imageFB is always equal to nil, even if the photo is there.

Any suggestions on how to fix that?

Firebase includes FirebaseUI, which helps managing image downloading / caching. Following the documentation, you should be able to download and display an image in a few simple lines of code.

I suggest you take a look at documentation . The link will take you to the image downloading section with an example on how to install and use it.

Try this let us know if works.

 fbUser = Auth.auth().currentUser
 let storage = Storage.storage()
 let storageRef = storage.reference(forURL: "somepath.some")
 let profilePicRef = storageRef.child(fbUser.uid+"_profile_pic.jpg")

// give your db ref var here
 let ref = Database.database().reference()
 let usersRef = ref.child("users").child(uid!)

 var picArray: [UIImage]()

Download:

usersRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in

  // Get download URL from snapshot
  let downloadURL = snapshot.value() as! String

  profilePicRef.downloadURL(completion: { (url, error) in
            let data = Data(contentsOf: url!)
            let image = UIImage(data: data! as Data)
            picArray.append(image)
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM