Search code examples
iosfacebook-graph-apiuiimageviewswift5

Showing a user's Facebook Picture using Graph API in Swift 5


My app can successfully retrieve a user's profile picture URL as a link and it prints it out to the console. However, I to convert this link into an image that is displayed in the UIImageView on the storyboard file.

The code is as follows:

import Foundation
import FacebookCore
import FacebookLogin

class HomeAfterLogInViewController: UIViewController
{
    // Links to UIImageView on storyboard
    @IBOutlet weak var imageView: UIImageView!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        let requestMe = GraphRequest.init(graphPath: "me", parameters: ["fields" : "id,name,email,picture.type(large)"])

        let connection = GraphRequestConnection()

        connection.add(requestMe, completionHandler:{ (connectn, userresult, error) in

            if let dictData: [String : Any] = userresult as? [String : Any]
                {
                    DispatchQueue.main.async
                        {
                            if let pictureData: [String : Any] = dictData["picture"] as? [String : Any]
                            {
                                if let data : [String: Any] = pictureData["data"] as? [String: Any]
                                {
                                    // prints out url of profile
                                    print(data["url"] as! String)
                                }
                            }
                        }
                  }
              })
              connection.start()
          }

    }

I have found several bits of code but none have worked.


Solution

  • You can use this library called Haneke, it's really good for caching and adds some helpful methods, once you install it you can do something like this

       guard let url = URL(string: urlAsString) else { return }
       yourImageView.hnk_setImageFromURL(url)