简体   繁体   中英

How to display profile image from new Firebase in iOS Swift?

The new Firebase lets you have a NSURL profile image property for the user, but I'm having trouble displaying it. Here is how I'm saving it......

let user = FIRAuth.auth()?.currentUser
if let user = user {
    let changeRequest = user.profileChangeRequest()
    changeRequest.photoURL = searchURL
    changeRequest.commitChangesWithCompletion { error in
        if let _ = error {
            print("Try Again")
        } else {
            print("Photo Updated")
            self.profileImage.image = image
        }
    }
}

And this is how I'm trying to retrieve it....

if let user = FIRAuth.auth()?.currentUser
{
    let name = user.displayName
    let pic = user.photoURL
    self.displayNameLBL.text = name
    if pic != nil
    {
        print(pic!)
        let urlString: String = pic!.path!
        self.profileImage.image = UIImage(named: urlString)
        //self.profileImage.image = UIImage(data: pic! as NSURL)
    }else
    {
        self.profileImage.image = UIImage(named: "imagePlaceholder")
    }
}

I'm getting user.displayName but not the image.

You are trying to display an URL not an image you need to download the image first you can use this extension:

 extension UIImageView {
        func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .ScaleAspectFit) {
            guard let url = NSURL(string: link) else { return }
            contentMode = mode
            NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
                guard
                    let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
                    let mimeType = response?.MIMEType where mimeType.hasPrefix("image"),
                    let data = data where error == nil,
                    let image = UIImage(data: data)
                    else { return }
                dispatch_sync(dispatch_get_main_queue()) {
                    self.image = image
                }
                }.resume()
        }
    }

usage :

imageView.downloadedFrom(stringURL, contentMode: .ScaleAspectFill)

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