Friday, January 15, 2016

Facebook SDK and Swift - Post a message using Graph API and post an image using FBSDKShareKit

This Facebook SDK example shows how to post a message using Graph API and post an image using FBSDKShareKit. The publish permission for publish_actions is required. The steps are as below:

1. Include the FBSDK frameworks into an Xcode project and modify AppDelegate.swift:

See this tutorial: Facebook SDK and Swift - Create a Facebook Login Button

2. Drag both fb-art.jpg file and the image file to be posted to Facebook into the Xcode project.

3. Modify ViewController.swift as:

import UIKit
import FBSDKLoginKit
import FBSDKShareKit

class ViewController: UIViewController, FBSDKLoginButtonDelegate, FBSDKSharingDelegate {
    
    var imageView : UIImageView!
    var label : UILabel!
    var imagePost : UIImage!
    var imageViewPost : UIImageView!
    var postButtonMsg : UIButton!
    var postButtonPhoto : UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        imageView = UIImageView(frame: CGRectMake(0, 0, 100, 100))
        imageView.center = CGPoint(x: view.center.x, y: 150)
        imageView.image = UIImage(named: "fb-art.jpg")
        view.addSubview(imageView)
        
        label = UILabel(frame: CGRectMake(0,0,200,30))
        label.center = CGPoint(x: view.center.x, y: 250)
        label.text = "Not Logged In"
        label.textAlignment = NSTextAlignment.Center
        view.addSubview(label)
        
        let loginButton = FBSDKLoginButton()
        loginButton.center = CGPoint(x: view.center.x, y: 300)
        loginButton.delegate = self
        loginButton.publishPermissions = ["publish_actions"]
        view.addSubview(loginButton)
        
        imagePost = UIImage(named: "image.jpg")
        
        imageViewPost = UIImageView(frame: CGRectMake(0, 0, 100, 100))
        imageViewPost.center = CGPoint(x: view.center.x, y: 400)
        imageViewPost.image = imagePost
        imageViewPost.contentMode = UIViewContentMode.ScaleAspectFit
        view.addSubview(imageViewPost)
        
        postButtonMsg = UIButton(frame: CGRectMake(0, 0, 300, 30))
        postButtonMsg.center = CGPoint(x: view.center.x, y: 480)
        postButtonMsg.setTitle("Post a Message", forState: UIControlState.Normal)
        postButtonMsg.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        postButtonMsg.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        postButtonMsg.addTarget(self, action: "btnPostMsg:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(postButtonMsg)
        
        postButtonPhoto = UIButton(frame: CGRectMake(0, 0, 300, 30))
        postButtonPhoto.center = CGPoint(x: view.center.x, y: 520)
        postButtonPhoto.setTitle("Post a Photo", forState: UIControlState.Normal)
        postButtonPhoto.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        postButtonPhoto.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        postButtonPhoto.addTarget(self, action: "btnPostPhoto:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(postButtonPhoto)
        
        getFacebookUserInfo()
    }
    
    func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
        print("didCompleteWithResult")
        
        getFacebookUserInfo()
    }
    
    func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
        print("loginButtonDidLogOut")
        imageView.image = UIImage(named: "fb-art.jpg")
        label.text = "Not Logged In"
        buttonEnable(false)
    }
    
    func getFacebookUserInfo() {
        if(FBSDKAccessToken.currentAccessToken() != nil)
        {
            
            buttonEnable(true)
            
            //print permissions, such as public_profile
            print(FBSDKAccessToken.currentAccessToken().permissions)
            let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "id, name, email"])
            graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
                
                self.label.text = result.valueForKey("name") as? String
                
                let FBid = result.valueForKey("id") as? String
                
                let url = NSURL(string: "https://graph.facebook.com/\(FBid!)/picture?type=large&return_ssl_resources=1")
                self.imageView.image = UIImage(data: NSData(contentsOfURL: url!)!)
            })
        } else {
            buttonEnable(false)
        }
    }
    
    func buttonEnable(enable: Bool) {
        if enable {
            postButtonMsg.alpha = 1
            postButtonMsg.enabled = true
            postButtonPhoto.alpha = 1
            postButtonPhoto.enabled = true
            imageViewPost.alpha = 1
        } else {
            postButtonMsg.alpha = 0.3
            postButtonMsg.enabled = false
            postButtonPhoto.alpha = 0.3
            postButtonPhoto.enabled = false
            imageViewPost.alpha = 0.3
        }
    }
    
    func btnPostMsg(sender: UIButton) {
        
        if FBSDKAccessToken.currentAccessToken().hasGranted("publish_actions") {
            
            FBSDKGraphRequest.init(graphPath: "me/feed", parameters: ["message" : "Posted with FBSDK Graph API."], HTTPMethod: "POST").startWithCompletionHandler({ (connection, result, error) -> Void in
                if let error = error {
                    print("Error: \(error)")
                } else {
                    self.alertShow("Message")
                }
            })
        } else {
            print("require publish_actions permissions")
        }
    }

    func btnPostPhoto(sender: UIButton) {
        if FBSDKAccessToken.currentAccessToken().hasGranted("publish_actions") {
            let content = FBSDKSharePhotoContent()
            content.photos = [FBSDKSharePhoto(image: imagePost, userGenerated: true)]
            FBSDKShareAPI.shareWithContent(content, delegate: self)
        } else {
            print("require publish_actions permissions")
        }
    }
    
    func sharer(sharer: FBSDKSharing!, didCompleteWithResults results: [NSObject : AnyObject]!) {
        print("didCompleteWithResults")
        alertShow("Photo")
    }
    
    func sharer(sharer: FBSDKSharing!, didFailWithError error: NSError!) {
        print("didFailWithError")
    }
    
    func sharerDidCancel(sharer: FBSDKSharing!) {
        print("sharerDidCancel")
    }
    
    func alertShow(typeStr: String) {
        let alertController = UIAlertController(title: "", message: typeStr+" Posted!", preferredStyle: UIAlertControllerStyle.Alert)
        alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
        presentViewController(alertController, animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Result:

The image to be posted to Facebook and the two post buttons are disabled while not logged in.


Login Review for this app is required by Facebook because the permission for publish_actions is enabled.


A successful login shows the user profile picture.


 Press the two post buttons. An alert dialog is shown after a successful post.

Switch to the Facebook app. The message and photo have been successfully posted.

1 comment: