mercredi 31 décembre 2014

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) http://ift.tt/1ELj3F8


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!




Aucun commentaire:

Enregistrer un commentaire