[Solved] How to take cover_photo from Facebook in swift 2.0


Here’s a working example using fb sdk in swift. The docs did help but they’re not a copy paste kind of example..
I needed to get the cover photo of a page so in the graphPath I used page id. This parameter can be easily changed to fit users / events / etc…

let request = FBSDKGraphRequest(graphPath: "\\(page.id)?fields=cover", parameters: [
  "access_token": "your_access_token"
], HTTPMethod: "GET")
request.startWithCompletionHandler({(connection , result , error) in
  if ((error) != nil) {
    print("Error in fetching cover photo for \\(page.id): \(error)", terminator: "")
  }
  else {
    if let data = result["cover"] as? NSDictionary {
      self.fetchImageFromUrl(data["source"] as! String, cb: {(image: UIImage) -> Void in
        //do something with image
      })
    }
  })

func fetchImageFromUrl(url: String, cb: (UIImage) -> Void) {
  let urlObj = NSURL(string: url)!
  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    let data = NSData(contentsOfURL: urlObj)
    dispatch_async(dispatch_get_main_queue(), {
      let image = UIImage(data: data!)!
      cb(image)
    });
  }
}

P.S – I’m a newbie in swift / ios so this code might not be the best. Comments will be appreciated.

solved How to take cover_photo from Facebook in swift 2.0