Fetch and Display User’s Facebook Photos

In this short Swift code example we will use FBSDKGraphRequest from Facebook iOS SDK to fetch user’s Facebook photos. The code example on this page will cover:

  • Import FBSDKCoreKit
  • Check if user is logged in and an access token can be read
  • Create UICollectionView
  • Use FBSDKGraphRequest to fetch user’s Facebook photos
  • Display each photo in a UICollectionView custom cell

If you run the code below, you should get a collection view with user’s Facebook photos listed like it is on the picture below:

Fetch user's Facebook photos

For the code below to work, user needs to be logged in with their Facebook profile. To let user login into your app with their Facebook account and for your app be able to fetch their Facebook photos, use the code snipped below:

Facebook Login Button and User Photos Read Permissions – Swift Code Example.

 
       let button = FBSDKLoginButton()
        button.center = view.center
        button.readPermissions = ["public_profile","email","user_photos"]
        self.view.addSubview(button)

Fetch and Display User’s Facebook Photos – Swift Code Example

  
 
import UIKit
import FBSDKCoreKit

class ListUserPhotosViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    var userPhotos:NSArray?
    var myCollectionView:UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Set up collection view
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: 60, height: 60)
        
        myCollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        myCollectionView.dataSource = self
        myCollectionView.delegate = self
        myCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
        myCollectionView.backgroundColor = UIColor.white
        self.view.addSubview(myCollectionView)
        
        
        if let _ = FBSDKAccessToken.current()
        {
            fetchListOfUserPhotos()
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func fetchListOfUserPhotos()
    {
        let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me/photos", parameters: ["fields":"picture"] )
        
  
        graphRequest.start(completionHandler: { (connection, result, error) -> Void in
            
            if ((error) != nil)
            {
                // Process error
                print("Error: \(error)")
            }
            else
            {
                print("fetched user: \(result)")
                
                let fbResult:[String:AnyObject] = result as! [String : AnyObject]
                
                self.userPhotos = fbResult["data"] as! NSArray?
                
                self.myCollectionView.reloadData()
 
            }
        })
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        var returnValue = 0
        
        if let userPhotosObject = self.userPhotos
        {
            returnValue = userPhotosObject.count
        }
        
        return returnValue
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath)
        myCell.backgroundColor = UIColor.black
        
        let userPhotoObject = self.userPhotos![indexPath.row] as! NSDictionary
        let userPhotoUrlString = userPhotoObject.value(forKey: "picture") as! String
        
        let imageUrl:URL = URL(string: userPhotoUrlString)!
        
        DispatchQueue.global(qos: .userInitiated).async  {
            
            let imageData:Data = try! Data(contentsOf: imageUrl)
            let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: myCell.frame.size.width, height: myCell.frame.size.height))
            
            // Add photo to a cell as a subview
            DispatchQueue.main.async {
                let image = UIImage(data: imageData)
                imageView.image = image
                imageView.contentMode = UIViewContentMode.scaleAspectFit
                myCell.addSubview(imageView)
            }
        }
        
        return myCell
    }

}

Checkout more Swift code examples at Swift Code Examples page.

[raw_html_snippet id=”cookbookpagecoursesheader”]

Unit Testing Swift Mobile App

Apply Test-Driven Development(TDD) process to iOS mobile app development in Swift Preview this video course.