Search code examples
swiftfacebook-graph-apiforced-unwrapping

Swift 2.3 Crash if Facebook profile cannot be returned


On my app the user has a profile picture, if signed in with Facebook the profile picture is set to there current Facebook profile picture. The issue i have is if the user signs into the app without Facebook the app crashes when trying to retrieve the Facebook data. How can i make it safe so if the Facebook data cannot be got then the profile picture can be set to blank.

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

}()

Solution

  • You are trying to create a NSData by force unwrapping an optional value, in this case photoUrl. I asumme that if the user did not log in with facebook, that value of that attribute is nil.

    What you should do is instead of force unwrapping the photoURL, you should check if it is nil first. To do this, you can use a guard, which is the recommended way to check for something

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

    This way, you know that the photoURL will not be nil, otherwise, it will returning the blank image.