Post on Facebook/ twitter in background in Swift - ios

Can anyone recommend me any swift library to post on facebook and twiiter.
I am trying this for now
if FBSDKAccessToken.currentAccessToken().hasGranted("publish_actions")
{
print("publish actions already granted.")
}
else
{
FBSDKGraphRequest.init(graphPath: "me/feed", parameters: ["message" : "hello world"], HTTPMethod: "POST").startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error == nil))
{
print("Post id: \(result.valueForKey("id") as! String)")
}
})
}
There is a situation that when user creates an event then my app will automatically post/tweet on its wall about the event he just created.
I am fimiliar about swifter and Facebook SDK but i am not sure if it will help me post in background

How luschn said, you can't post automatically, but you can ask user if he want to post event.
For facebook post just use Facebook SDK(https://developers.facebook.com/docs/ios), you have there instruction for installation. You can use "Posting Data" from https://developers.facebook.com/docs/ios/graph, but you need first to check if user give you right to post it.
For Twitter post, apple give you a library(Social.framework) can help you for post on Twitter. You can learn how use it from http://code.tutsplus.com/tutorials/social-framework-fundamentals--mobile-14333. Also you can use this framework for facebook post.

guys i know i asked a silly question , but after upgrading my project to swift 2.0 and fb sdk 4.6 i did the posting
var params: NSDictionary = NSDictionary()
let userInfo: AnyObject = LocalStore.userDetails()!
let name = userInfo["name"] as? String
params = ["message": msgString]
let request: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "/me/feed", parameters: params as [NSObject: AnyObject], HTTPMethod: "POST")
request.startWithCompletionHandler({ (connection, result, error) -> Void in })
This way you can post any message in background... but do check for fb login and ask for publishPermission(loginWithPublishPermission).

Related

Facebook graph API link parameter returning nil

I am trying to store a logged in facebook user's facebook username (eg www.facebook.com/james.dean01) in order to connect people via messenger (similar to How to open Facebook Messenger and direct to someone?). I am configuring a button which will send a user directly to someones messenger chat but to do so I need their username/facebook URL. I am attempting to use the "link" property (Facebook graph API: https://developers.facebook.com/docs/graph-api/reference/user) to obtain a link to the user's profile which could be used for this purpose, only the link property (printed) returns nil. I am not sure what I am doing wrong. The aim is that each time a user logs in the data is read and the database is updated. Below is the code.
Any help would be greatly appreciated!
import FacebookCore
class FacebookService {
static let instance = FacebookService()
let params = ["fields": "email, first_name, last_name, link, picture, name"]
func recordUserData() {
let graphRequest = GraphRequest(graphPath: "me", parameters: params)
graphRequest.start {
(urlResponse, requestResult) in
switch requestResult {
case .failed(let error):
print("error in graph request:", error)
break
case .success(let graphResponse):
if let responseDictionary = graphResponse.dictionaryValue {
print(responseDictionary)
let link = responseDictionary["link"] as? String
let email = responseDictionary["email"] as? String
let fbId = responseDictionary["id"] as? String
let name = responseDictionary["name"] as? String
let picture = responseDictionary["picture"] as? NSDictionary
let data = picture!["data"] as? NSDictionary
let url = data!["url"] as? String
print("Link: \(link)")
print(url)
}
}
}
}
}
You need to ask for the necessary permission, https://developers.facebook.com/docs/facebook-login/permissions#reference-user_link
And the use of this permission requires review by Facebook, before you can use it in your live app.
Not sure you would get this through review though, because what you would be doing is essentially what it says there is a not allowed use case:
Attempt to programmatically determine someone's Facebook username or canonical User ID.
So no guarantee Facebook will approve this; you can only try and submit it for review and see what feedback you get.

How to retrieve Email from Facebook SDK

Note: please do not close as duplicate, I went through almost every existing thread here on Stackoverflow, but my problem is still not solved.
This is my Swift 3 function with the latest Facebook SDK:
let req = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email,name"], tokenString: token?.tokenString, version: nil, httpMethod: "GET")
_ = req?.start(completionHandler: { (connection, result, error : Error?) -> Void in
if(error == nil) {
print("result \(result)")
} else {
print("error \(error!)")
}
})
Result:
result Optional({
id = 102080884567XXXXX;
name = "David Seek";
})
Email permission is approved:
Also the App is in live mode:
I have checked the reference guide, but I can't find my mistake.
My problem is, that I'm saving the facebookID as Email adress into my backend and I'm trying to figure out why... Therefore I have tried the provided code on top, but I'm not receiving the Email.
let result = FBSDKApplicationDelegate.sharedInstance().application(application,
open: url,
sourceApplication: sourceApplication,
annotation: annotation)
if result {
let token = FBSDKAccessToken.current()
let fieldsMapping = [
"id" : "facebookId",
"name" : "name",
"birthday": "birthday",
"first_name": "fb_first_name",
"last_name" : "fb_last_name",
"gender": "gender",
"email": "email"
]
backendless?.userService.login(withFacebookSDK: token, fieldsMapping: fieldsMapping, response: { (user: BackendlessUser?) in
}, error: { (fault: Fault?) -> Void in
print("Server reported an error: \(fault)")
})
}
I'm receiving every information, but the Email...
What am I missing? Help is very appreciated.
Email permission is granted:
That is not what that screenshot shows. It shows that it is approved, meaning your app can ask users for it. But it still has to ask.
Make sure that has happend successfully - either by debugging the access token, or via an API call to /me/permissions
You need to ask the user for permission during login.

Facebook Login doesn't fetching all User's profile information in swift

In my app I implemented FacebookLogin accessing permissions:
let facebookReadPermissions = ["public_profile", "email", "user_friends"]
Once all permissions granted, I am calling graph API for fetching user's profile info using:
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
It is returning just two values: { id = 86160953055XXXX; name = "Devendranath Reddy"; }
I want Address, email, phone, first and last names also.
What is wrong here.
I even enabled for live access in developer.apple.com -> MyApp -> Settings
Please help me out.
Thanks in advance.
try this out, you need to set the parameters value:
so for Swift it would be this:
parameters:#{#"fields": #"id, name"}
In swift it would be something similar
something like this:
let params = ["fields": "email, friends"]
so:
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: params)
Add whatever fields you want to add, like "first_name" "last_name" etc, etc.
let params = ["fields": "email, first_name, gender, last_name, location"]
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: params)
graphRequest.startWithCompletionHandler(
{
(connection, result, error) -> Void in
if ((error) != nil)
{
// Failure code goes here.
}
else
{
// Success code goes here
println("User Name is: \(userName)")
println("User Email is: \(userMail)")
println("Gender is: \(gender)")
}
})
This request won't grab all the information until your app is reviewed by Facebook's app review. It will only give you access to the public profile info, regardless of what permissions the user accepts.

Trouble retrieving list of facebook friends from json data in swift

I am using FBSDK in my Swift iOS application and currently I am trying to retrieve the list of friends who also use my app. I have two-three people who should show up but whenever I search the graphrequest result for friends it returns nil..
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result:AnyObject!, error) -> Void in
if ((error) != nil)
{
// Process error
println("Error: \(error)")
}
else
{
//get Facebook ID
let faceBookID: NSString = result.valueForKey("id") as NSString
//get username
let userName : NSString = result.valueForKey("name") as NSString
//get facebook friends who use app
let friendlist: AnyObject = result.valueForKey("friends") as AnyObject
}
I have the "email", "user_friends", and "public_profile" permissions which should be enough to retrieve this information. Any Ideas on what I am doing wrong?? this is doing my head in as my friend doing an android version has successfully got his working..
My problem here was that I never Actually requested for the list of friends in my facebook graph request...
after replacing FBSDKGraphRequest(graphPath: "me", parameters: nil)
with FBSDKGraphRequest(graphPath: "me?fields=id,name,friends", parameters: nil)
I was able to retrieve the list of friends because the response actually contained information for this. A very trivial mistake on my part.
In v2.0 of the Graph API, you must request the user_friends permission
from each user. user_friends is no longer included by default in every
login. Each user must grant the user_friends permission in order to
appear in the response to /me/friends.
see here : https://developers.facebook.com/bugs/1502515636638396/

Share in facebook using Swift

I need to share text, Image And link without using "SLComposeViewController" in Swift.
I have used Parse for this. But don't able to Post
Below is my Code:
func postToFacebook(message : String) {
var postParams =
["https://developers.facebook.com/ios" : "link",
"https://developers.facebook.com/attachment/iossdk_logo.png":"picture",
"Facebook SDK for iOS":"name",
message: "message",
"Build great social apps and get more installs.":"caption",
"The Facebook SDK for iOS makes it easier and faster to develop Facebook integrated iOS apps." : "description",
];
let req = FBRequest(session: PFFacebookUtils.session(), graphPath: "me/feed", parameters: postParams, HTTPMethod: "POST")
req.startWithCompletionHandler { (connection, result, error) -> Void in
if error != nil {
println("\(error.description)")
} else {
println("posted to facebook")
}
}
}
And getting this Error:
error = {
code = 200;
message = "(#200) The user hasn't authorized the application to perform this action";
type = OAuthException;
};
Please anybody help on doing this

Resources