如何在iOS Swift中显示来自新Firebase的个人资料图片?

时间:2016-07-12 00:56:02

标签: ios swift firebase firebase-authentication

新的Firebase可让您为用户提供NSURL配置文件图片属性,但我无法显示它。这就是我如何拯救它......

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
        }
    }
}

这就是我试图检索它的方式....

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")
    }
}

我得到了user.displayName但没有得到图像。

1 个答案:

答案 0 :(得分:1)

您尝试显示的网址不是您下载图片所需的图片,您可以使用此扩展程序:

 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()
        }
    }

用法:

imageView.downloadedFrom(stringURL, contentMode: .ScaleAspectFill)