2017-02-07 8 views
1

私のアプリでは、ユーザーはプロフィールの画像を持っています。Facebookにサインインした場合、プロフィールの画像は現在のFacebookプロフィールの画像に設定されています。私が持っている問題は、ユーザーがFacebookなしでアプリにサインインして、Facebookのデータを取得しようとしたときにアプリケーションがクラッシュした場合です。どのように私はそれを安全にすることができますので、Facebookのデータが取得できない場合は、プロフィールの画像を空白に設定することができます。Swift 2.3 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 

}() 
+0

「[致命的なエラー:任意の値をアンラッピングしている間に予期せぬエラーが検出されました」とはどういう意味ですか?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found- nil-while-unwrapping-an-optional-valu) – rmaddy

答えて

0

任意の値をアンラップして強制的にNSDataを作成しようとしています(この場合はphotoUrl)。ユーザーがFacebookにログインしていない場合、その属性の値はnilであることに注意してください。

photoURLを強制的にアンラッピングするのではなく、最初にゼロでないかどうかを確認する必要があります。これを行うには、あなたは、それ以外の場合は空白の画像を返します、あなたは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 

}() 

この方法を確認するために推奨される方法であるガードを、使用することができます。

関連する問題