Swift 2.3 无法返回 Facebook 个人资料时崩溃

Swift 2.3 Crash if Facebook profile cannot be returned

在我的应用程序上,用户有个人资料图片,如果使用 Facebook 登录,个人资料图片将设置为当前的 Facebook 个人资料图片。我遇到的问题是,如果用户在没有 Facebook 的情况下登录应用程序,则在尝试检索 Facebook 数据时应用程序会崩溃。我怎样才能确保安全,如果无法获取 Facebook 数据,则可以将个人资料图片设置为空白。

lazy var profileImageView: UIImageView = {


    let user = FIRAuth.auth()?.currentUser
    let photoUrl = user?.photoURL
    let data = NSData(contentsOfURL: photoUrl!) 
        let profileView = UIImageView()
        profileView.image = UIImage(data: data!)
        profileView.contentMode = .ScaleAspectFill

        profileView.layer.cornerRadius = 16
        profileView.layer.masksToBounds = true

        profileView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView)))
        profileView.userInteractionEnabled = true
        return profileView

}()

您正在尝试通过强制展开可选值来创建 NSData,在本例中为 photoUrl。我假设如果用户没有使用 facebook 登录,则该属性的值为 nil。

你应该做的不是强制展开 photoURL,你应该先检查它是否为 nil。为此,您可以使用守卫,这是检查某些东西的推荐方法

lazy var profileImageView: UIImageView = {
    let user = FIRAuth.auth()?.currentUser
    let photoUrl = user?.photoURL

    guard let photoUrl = user?.photoURL else {
        return UIImageView()
        //Here do the cusomization of the blank image before 
        //returning it
    }

    let data = NSData(contentsOfURL: photoUrl) 
    let profileView = UIImageView()
    profileView.image = UIImage(data: data!)
    profileView.contentMode = .ScaleAspectFill

    profileView.layer.cornerRadius = 16
    profileView.layer.masksToBounds = true

    profileView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImageView)))
    profileView.userInteractionEnabled = true
    return profileView

}()

这样就知道photoURL不会为nil,否则返回的是空白图片。