skip to Main Content

I am using Facebook’s SDKs to allow a user to login to my app, I would like the app to display the user’s profile picture. I have the following storyboards and Swift files:

  • Main.storyboard & ViewController.swift

  • HomeAfterLogIn.storyboard & HomeAfterLogInViewController.swift

"Main" contains the view controller that the user signs in with and the code for the user to sign in with is as follows:

import UIKit
import FacebookLogin

class ViewController: UIViewController
{
    override func viewDidLoad()
    {
        super.viewDidLoad()

        if AccessToken.current != nil
        {
            // Already logged-in
            // Redirect to Home View Controller
            goToHome()
        }

        // Add LoginButton
        let loginButton = FBLoginButton(permissions: [ .publicProfile, .email, .userFriends ])
        let screenSize:CGRect = UIScreen.main.bounds
        let screenHeight = screenSize.height // real screen height
        //let's suppose we want to have 10 points bottom margin
        let newCenterY = screenHeight - loginButton.frame.height - 20
        let newCenter = CGPoint(x: view.center.x, y: newCenterY)
        loginButton.center = newCenter
        view.addSubview(loginButton)

        // Triggered after every successfully login / logout
        NotificationCenter.default.addObserver(forName: .AccessTokenDidChange, object: nil, queue: OperationQueue.main) { [weak self] _ in
            if AccessToken.current != nil {
                // Successfully just Logged in
                // Redirect to Home View Controller
                self?.goToHome()
            } else {
                // Successfully just Logged out
            }
        }
    }

    func goToHome() {
        let storyboard = UIStoryboard(name: "HomeAfterLogIn", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "HomeAfterLogInViewController") // I called mine like that (check screenshot below)
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

This code shows the log in with Facebook button and if the user enters a successful log in the

func goToHome()

Sends the user to the HomeAfterLogIn.storyboard and this is where I would like the user’s profile picture to be shown.

I found this code on Facebooks Graph API website:

FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
    initWithGraphPath:@"/100046232170264/picture"
           parameters:@{ @"redirect": @"false",}
           HTTPMethod:@"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
    // Insert your code here
}];

The values above are related to my app. When I insert this code into my HomeAfterLogInViewController.swift file is just produces the following errors:

enter image description here

enter image description here

enter image description here

Am I entering the code wrong? Is it a previous version of Swift, mine is swift 4 or 5? This is my first time using Facebook SDKs.

After comments on post

(Keshu R.) Converted obj-c to Swift:

let request = FBSDKGraphRequest(graphPath: "/100046232170264/picture", parameters: [
    "redirect": "false"
], httpMethod: "GET")
request.start(withCompletionHandler: { connection, result, error in
    // Insert your code here
})

(Karol Zmysłowski) Errors from code:

enter image description here

(Keshu R.) UI items in HomeAfterLogIn.storyboard:

enter image description here

2

Answers


  1. import FacebookCore
    import FacebookLogin
    
    Profile.loadCurrentProfile(completion: { profile, error in
        if let profile = profile {
            let imageURL = profile.imageURL(forMode: .square, size: CGSize(width: 200.0, height: 200.0))
        }
    })
    
    Login or Signup to reply.
  2. I would suggest to create a custom button and add action to it

    // import 
    import FBSDKCoreKit
    import FBSDKLoginKit
    
    
    class LoginVC : UIViewController {
        // create an IBAction and call the function inside it
        @IBAction func facebookLoginBtnPressed(_ sender : Any) {
            fetchFacebookFields()
        }
        // this function will return all the details and you can store it in userdefaults
        func fetchFacebookFields() {
            LoginManager().logIn(permissions: ["email","public_profile"], from: nil) {
                (result, error) -> Void in
                if let error = error {
                    print(error.localizedDescription)
                    return
                }
                guard let result = result else { return }
                if result.isCancelled { return }
                else {
                    GraphRequest(graphPath: "me", parameters: ["fields" : "first_name, last_name, email"]).start() {
                        (connection, result, error) in
                        if let error = error {
                            print(error.localizedDescription)
                            return
                        }
                        if
                            let fields = result as? [String:Any],
                            let userID = fields["id"] as? String,
                            let firstName = fields["first_name"] as? String,
                            let lastName = fields["last_name"] as? String,
                            let email = fields["email"] as? String
    
                        {
                            let facebookProfileUrl = "http://graph.facebook.com/(userID)/picture?type=large"
                            print("firstName -> (firstName)")
                            print("lastName -> (lastName)")
                            print("email -> (email)")
                            print("facebookProfileUrl -> (facebookProfileUrl)")
                            APPDELEGATEOBJ.makeRootVC(vcName : "MainTabBarVC")
    
                        }
                    }
                }
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search