SAMIR RATHOD
SAMIR RATHOD

Reputation: 3506

how to share Image on Facebook using Swift in IOS

I want to share an image on Facebook using swift language. I am able to share image using Objective C. I tried using

1) How to Share image + text with facebook in swift iOS?

but not working, then I tried using other options but not able to share image using swift language. then I tried this

2) https://github.com/rajeshsegu/facebook-ios-swift/tree/master/FBApp

I copied Facebook.swift and write another function for share image my code for Facebook.swift

import Foundation
import Social

let FB = Facebook();

class Facebook {

    var fbSession:FBSession?

    init(){
        self.fbSession = FBSession.activeSession();
    }

    func hasActiveSession() -> Bool{
        let fbsessionState = FBSession.activeSession().state;
        if ( fbsessionState == FBSessionState.Open
            || fbsessionState == FBSessionState.OpenTokenExtended ){
                self.fbSession = FBSession.activeSession();
                return true;
        }
        return false;
    }

    func login(callback: () -> Void){

        let permission = ["publish_actions","email","user_location","user_birthday","user_hometown","user_photos","user_about_me"];
        let activeSession = FBSession.activeSession();
        let fbsessionState = activeSession.state;
        var showLoginUI = true;

        if(fbsessionState == FBSessionState.CreatedTokenLoaded){
            showLoginUI = false;
        }

        if(fbsessionState != FBSessionState.Open
            && fbsessionState != FBSessionState.OpenTokenExtended){

                FBSession.openActiveSessionWithPublishPermissions(permission, defaultAudience: FBSessionDefaultAudience.Friends, allowLoginUI: showLoginUI, completionHandler: { (session:FBSession!, state:FBSessionState, error:NSError!) -> Void in

                    if(error != nil){
                        println("Session Error: \(error)");
                    }
                    self.fbSession = session;
                   // println("Session : \(self.fbSession?.permissions)");
                    callback();

                })

//                FBSession.openActiveSessionWithReadPermissions(
//                    permission,
//                    allowLoginUI: showLoginUI,
//                    completionHandler: { (session:FBSession!, state:FBSessionState, error:NSError!) in
//
//                        if(error != nil){
//                            println("Session Error: \(error)");
//                        }
//                        self.fbSession = session;
//                        println("Session : \(self.fbSession?.permissions)");
//                        callback();
//                        
//                    }
//                );
                return;
        }

        callback();

    }

    func logout(){
        self.fbSession?.closeAndClearTokenInformation();
        self.fbSession?.close();
    }

    func getInfo(){
        FBRequest.requestForMe()?.startWithCompletionHandler({(connection:FBRequestConnection!, result:AnyObject!, error:NSError!) in

            if(error != nil){
                println("Error Getting ME: \(error)");
            }

            println("\(result)");
            var dictData:NSDictionary!=result as? NSDictionary
        });
    }

    func handleDidBecomeActive(){
        FBAppCall.handleDidBecomeActive();
    }

    func shareImage (imageName:UIImageView){
        let fbsessionState = FBSession.activeSession().state;
        if(fbsessionState == FBSessionState.Open)
        {
            //var arr : NSArray=NSArray(array: ["publish_actions"])
            self.fbSession?.requestNewPublishPermissions(["publish_actions"], defaultAudience:FBSessionDefaultAudience.Friends, completionHandler: { (session:FBSession!, error:NSError!) -> Void in
                if(error == nil){
                    var requestConneciton:FBRequestConnection=FBRequestConnection()
                    requestConneciton.errorBehavior=FBRequestConnectionErrorBehavior.None

                    requestConneciton.addRequest(FBRequest(forUploadPhoto:imageName.image)) { (connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
                        println("\(error)");
                        println("\(result)");
                        //[self showAlert:@"Photo Post" result:result error:error];
                    }
                    requestConneciton.start()

                }
                else if(error.fberrorCategory == FBErrorCategory.UserCancelled){
                    var alt:UIAlertView!=UIAlertView(title:"Permission denied", message:"Unable to get permission to post", delegate:nil, cancelButtonTitle:"Ok")
                    alt.show()
                }

            })
        }
    }

    func showAlert(msg:NSString!,result:AnyObject,error:NSError!) {
        var alertTitle:NSString!
        var alertMsg:NSString!;
        if (error == nil) {
            if((error.fberrorUserMessage != nil && FBSession.activeSession().isOpen) ) {
                alertTitle = "";
            }
            else{
                // Otherwise, use a general "connection problem" message.
                alertMsg = "Operation failed due to a connection problem, retry later.";
            }
        }
        else {
            //var dictResult:NSDictonary = result as NSDictionary
            alertMsg="Successfully posted "
            var alertObj:UIAlertView!=UIAlertView(title:"Demo App", message:alertMsg, delegate:nil, cancelButtonTitle:"Ok");
            alertObj.show();
        }
    }

    func performPublishAction(action:() -> Void){

        var arrP:NSArray!=NSArray(array: ["publish_actions"]);

        fbSession?.requestNewPublishPermissions(arrP, defaultAudience:FBSessionDefaultAudience.Friends, completionHandler: { (session:FBSession!, error:NSError!) -> Void in

            if(error == nil){
                action()
            }
            else if(error.fberrorCategory == FBErrorCategory.UserCancelled){
                var alt:UIAlertView!=UIAlertView(title:"Permission denied", message:"Unable to get permission to post", delegate:nil, cancelButtonTitle:"Ok")
                alt.show()
            }

        })
    }
}

and In ViewController.swift

import UIKit

class ViewController: UIViewController,FBLoginViewDelegate {

    @IBOutlet var imageObj:UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func btnFBLoginClick(sender: UIButton) {
        FB.login(self.handleLogin);
    }

    func handleLogin(){
        println("SUCCESS");
        FB.getInfo();
    }

    @IBAction func btnShareclick(sender: UIButton) {
        FB.shareImage(imageObj) 
    }

}

Login button click working perfect and it can fetch all data of login user, but when i share the image using FB.shareImae(imageObj) its give me a permission error, I am working on this point from last 2 days now I am stuck. if i write same code in Objective C its working fine.

eror :

permissions:(
    "public_profile",
    email,
    "user_friends"
)>, com.facebook.sdk:ParsedJSONResponseKey={
    body =     {
        error =         {
            code = 200;
            message = "(#200) Permissions error";
            type = OAuthException;
        };
    };
    code = 403;
}}

Can any one help me? to find out this problem...

I don't want to use SLComposeViewController, I want to use Facebook framework.

Thank you in advance!

Upvotes: 1

Views: 7344

Answers (5)

iOSJit
iOSJit

Reputation: 21

check this guy's answer https://stackoverflow.com/a/58481784/12250012

also now facebook is not allowing programatically.

Upvotes: 1

Nakul Sharma
Nakul Sharma

Reputation: 610

I have had the same issue. I have solve it by writing such code. If you have an active Facebook session this code is perfectly work.

 func performPublishAction(callBack:() -> Void){
        self.fbSession?.requestNewPublishPermissions(["publish_actions"], defaultAudience: FBSessionDefaultAudience.Friends, completionHandler: {(session:FBSession!, error:NSError!)->Void in
            if error == nil {

                callBack()
            }else{
                println(error)
            }
        })
    }




    func shareImage (imageName:UIImage){
            var requestConneciton:FBRequestConnection=FBRequestConnection()
            requestConneciton.errorBehavior=FBRequestConnectionErrorBehavior.None

            requestConneciton.addRequest(FBRequest(forUploadPhoto:imageName)) { (connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
                println("\(error)");
                println("\(result)");

            }
            requestConneciton.start()
        }

use of these methods will be as:

    facebookHelper.performPublishAction { () -> Void in
       facebookHelper.shareImage(self.itemImage)
        //NkCommonClass.displayToast("Posted successfully on your wall.")
    }

Upvotes: 0

Marie Dm
Marie Dm

Reputation: 2727

I solved my problem (I put my comment here cause I don't have enough place to explain). So I was trying to share a link on Facebook. First I was wrong with the params, I was writing

var params=["http://www.google.com":"link"]

and the correct way is

var params=["link":"http://www.google.com"] 

(Because of the way it's written in Obj-C on dev.facebook.com I got confused).

Secondly, if I follow the logic of the original github project, I call my function this way:

FB.performPublishAction(self.shareLinkOnFB)

where performPublishAction (in the Facebook class) ask for the new publish permissions:

func performPublishAction(action:() -> Void){
fbSession?.requestNewPublishPermissions(fbSettings.publishPermissions, defaultAudience: fbSettings.publishAudience, completionHandler: {(session:FBSession!, error:NSError!)->Void in
            if error==nil {
                println("perform publish action / no error")
                action()
            }else{
                println("perform publish action / error: \(error.localizedDescription)")
                println(error)
            }
        })

and shareLinkOnFb function calls FB.requestToShareLink():

func shareLinkOnFB(){
    FB.requestToShareLink()
}

func requestToShareLink(){
var params=["link":"\(self.link)", "message":"\(self.message)"]
FBRequestConnection.startWithGraphPath("/me/feed", parameters:params, HTTPMethod: "POST", completionHandler: { (connection:FBRequestConnection!, result:AnyObject!, error:NSError!) in
    if error != nil {
        println("Request to share link / An error occurred: \(error.localizedDescription)")
        println(error)
        //handle error
    }else{
        println("link successfully posted: \(result)")
    }
    })
}

I'm not sure you have the same problem but I hope it can help you.

Upvotes: 1

user4385051
user4385051

Reputation:

You have to request in your facebook app the "publish_actions" permissions.

Upvotes: 0

Christos Chadjikyriacou
Christos Chadjikyriacou

Reputation: 3759

This is a code i created in an old project. Give it a try ;)

  @IBAction func btn_Share(sender: AnyObject) {

    let facebookPost = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
    facebookPost.completionHandler = {
        result in
        switch result {
        case SLComposeViewControllerResult.Cancelled:
            //Code to deal with it being cancelled
            break

        case SLComposeViewControllerResult.Done:
            //Code here to deal with it being completed
            break
        }
    }

    facebookPost.setInitialText("Test Facebook") //The default text in the tweet
    facebookPost.addImage(masked_image) //Add an image
    facebookPost.addURL(NSURL(string: "http://facebook.com")) //A url which takes you into safari if tapped on

    self.presentViewController(facebookPost, animated: false, completion: {
        //Optional completion statement
    })
    }`

Upvotes: 2

Related Questions