Share in facebook using Swift - ios

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

Related

Get insights/page_fans for a Facebook page from Facebook's open graph

I'm trying to get the number of fans that a music artist has on their Facebook page, but it's not working. I've combed through the FBAPI docs as well as SO and still nothing. Here's my code:
func getHolychildInfo() {
//Make request
let newGraphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "/holychildmusic/insights/page_fans", parameters: ["period" : "lifetime", "show_description_from_api_doc" : "true", "fields": "read_insights"], httpMethod: "GET")
newGraphRequest.start(completionHandler: { (connection, result, error) in
if ((error) != nil) {
print("Holychild error getting insights: \(error.debugDescription)")
} else {
print("\nHolychild insights result:\n\n\(result)")
}
})
}
Here's my result:
data = (
);
paging = {
next = "https://graph.facebook.com/v2.8/holychildmusic/insights/page_fans?access_token=EAAIB5k3aWEEBAHBD9lZC5AAzZAVV8K8CGBfqaxcrLdZA7oZB2Gdar8cQphXj4VciloZAnZBKp5ZA59BmGloSNz847nFqZCTVsYZCl9rrOk88OnfCnDwwADKnkOO5EUhGumEbW96riHplgfBLdnZAEYmB2Qz4ZAH1sWbuftmGKDqPft4l5QAHSZAimIyI6sOHaKWiurRK201Af6NQCXGliZBsZAUYosUHttkUbo4CQZD&fields=read_insights&format=json&include_headers=false&period=lifetime&sdk=ios&show_description_from_api_doc=true&since=1487457711&until=1487716911";
previous = "https://graph.facebook.com/v2.8/holychildmusic/insights/page_fans?access_token=EAAIB5k3aWEEBAHBD9lZC5AAzZAVV8K8CGBfqaxcrLdZA7oZB2Gdar8cQphXj4VciloZAnZBKp5ZA59BmGloSNz847nFqZCTVsYZCl9rrOk88OnfCnDwwADKnkOO5EUhGumEbW96riHplgfBLdnZAEYmB2Qz4ZAH1sWbuftmGKDqPft4l5QAHSZAimIyI6sOHaKWiurRK201Af6NQCXGliZBsZAUYosUHttkUbo4CQZD&fields=read_insights&format=json&include_headers=false&period=lifetime&sdk=ios&show_description_from_api_doc=true&since=1486939311&until=1487198511";
};
As you can see, there is nothing in the "data" part of the response. The "page_fans" insights metric is supposed to return a number - among other things - but instead returns nothing.
All insights metrics besides the two public ones (page_fans_country and page_storytellers_by_country) require admin access to the page (admin user or page access token with read_insights permission.)
But the fan_count field of the page object is public, so just request that:
https://developers.facebook.com/tools/explorer/?method=GET&path=holychildmusic%3Ffields%3Dfan_count&version=v2.8

How to get email from twitter by fabric in iOS 9? [duplicate]

I have integrated twitter kit in my ios app by following https://dev.twitter.com/twitter-kit/ios/configure this. I could sign-in after authentication and see my twitter name easily but now i want to retrieve my email address so i used TWTRShareEmailViewController which presents user a share email view which returns null. I went through the docs where they mentioned about my app to be whitelisted for requesting email permission and said to fill up this form https://support.twitter.com/forms/platform am not getting what to do next? how to get i user email permission exactly? Suggest any help. Thanks in advance.
I didn't find a specific form to ask to be whitelisted neither. I went on their form link https://support.twitter.com/forms/platform and I checked the "I have an API policy question not covered by these points" option. They responded a few days after and asked me more information about the application and its app ID. I'm actually waiting for their answer.
EDIT:
So after several (a lot) emails with support#fabric.io and a few bugs I finally got whitelisted. But the option is currently unavailable with Fabric so you'll have to create a Twitter app on apps.twitter.com. Just send a mail with your app ID or your keys. They'll probably ask you a quick description of your app and it shouldn't take so much time to be whitelisted. Good luck!
After having a conversation with sdk-feedback#twitter.com, I got my App whitelisted. Here is the story:
Send mail to sdk-feedback#twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App. Mention in mail that you want to access user email address inside your App.
They will review your App and reply to you within 2-3 business days.
Once they say that your App is whitelisted, update your App's settings in Twitter Developer portal. Sign in to apps.twitter.com and:
On the 'Settings' tab, add a terms of service and privacy policy URL
On the 'Permissions' tab, change your token's scope to request email. This option will only been seen, once your App gets whitelisted.
It's time to code:
-(void)requestUserEmail
{
if ([[Twitter sharedInstance] session]) {
TWTRShareEmailViewController *shareEmailViewController =
[[TWTRShareEmailViewController alloc]
initWithCompletion:^(NSString *email, NSError *error) {
NSLog(#"Email %# | Error: %#", email, error);
}];
[self presentViewController:shareEmailViewController
animated:YES
completion:nil];
} else {
// Handle user not signed in (e.g. attempt to log in or show an alert)
}
}
Hope it helps !!!
Send email to sdk-feedback#twitter.com to whitelist your twitter login app first.
Swift 3.0 Code with fabric
#IBAction func btnTwitterAction(_ sender: AnyObject) {
Twitter.sharedInstance().logIn { (session, error) in
if session != nil {
print("signed in as \(session!.userName)");
let client = TWTRAPIClient.withCurrentUser()
let request = client.urlRequest(withMethod: "GET",
url: "https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true",
parameters: ["include_email": "true", "skip_status": "true"],
error: nil)
client.sendTwitterRequest(request) { response, data, connectionError in
if (connectionError == nil) {
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
print("Json response: ", json)
let firstName = json["name"]
let lastName = json["screen_name"]
let email = json["email"]
print("First name: ",firstName)
print("Last name: ",lastName)
print("Email: ",email)
} catch {
}
}
else {
print("Error: \(connectionError)")
}
}
} else {
NSLog("Login error: %#", error!.localizedDescription);
}
}
}
How to get email id in twitter ?
Step 1 : got to https://apps.twitter.com/app/
Step 2 : click on ur app > click on permission tab .
Step 3 : here check the email box
I've faced the same issue recently
Here is what you should try if you are using new twitter kit
Go to
https://apps.twitter.com/
Select permissions tab
Set it to Read Only
Code :
Twitter.sharedInstance().logIn(withMethods: [.webBased,.systemAccounts,.all]) {(session, error) -> Void in
if (session != nil) {
print("signed in as \(session?.userName)");
let client = TWTRAPIClient(userID: session?.userName)
client.loadUser(withID: (session?.userID)!, completion: { (user, error) in
let twitterClient = TWTRAPIClient.withCurrentUser()
let request = twitterClient.urlRequest(withMethod: "GET",
url: "https://api.twitter.com/1.1/account/verify_credentials.json",
parameters: ["include_email": "true", "skip_status": "true"],
error: nil)
twitterClient.sendTwitterRequest(request) { response, data, connectionError in
print(data!)
let s :String = String(data: data! as Data, encoding: String.Encoding.utf8)!
//
// let json = try JSONSerialization.jsonObject(with: responseData as Data, options: JSONSerialization.ReadingOptions.mutableLeaves) as? [String:AnyObject]
//
Twitter.sharedInstance().sessionStore.logOutUserID((session?.userID)!)
if let data = s.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
print(json!)
} catch {
print("Something went wrong")
}
}
}
})
} else {
}

Post on Facebook/ twitter in background in Swift

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).

How to tag a facebook page in FBSDK for iOS

While using the FBSDK for iOS, I am trying to attach/tag a relevant facebook page. Any pointers to their docs? I looked up some info on message_tags parameter but not sure how to use it.
let shareParams = ["message":"Check out this page #PAGE_NAME"]
let fbRequest = FBSDKGraphRequest.init(graphPath: "me/feed", parameters: shareParams, HTTPMethod: "POST")
fbRequest.startWithCompletionHandler { (connection :FBSDKGraphRequestConnection!, result, error) -> Void in
if let responseError = error {
if responseError.domain == FacebookSharerErrorDomain.FacebookAPIError.rawValue {
self.handleFacebookAPIError(responseError)
} else {
Error("Unable to share")
}
} else {
Success("Shared to Facebook")
}
}
I think this is what you looking for (if anchor didn't work refresh page. or search "Mentioning Friends or Pages" section).
Also look at taggable_friends endpoint.

how to request permission to retrieve user's email using twitter kit version 1.2.0 in ios8?

I have integrated twitter kit in my ios app by following https://dev.twitter.com/twitter-kit/ios/configure this. I could sign-in after authentication and see my twitter name easily but now i want to retrieve my email address so i used TWTRShareEmailViewController which presents user a share email view which returns null. I went through the docs where they mentioned about my app to be whitelisted for requesting email permission and said to fill up this form https://support.twitter.com/forms/platform am not getting what to do next? how to get i user email permission exactly? Suggest any help. Thanks in advance.
I didn't find a specific form to ask to be whitelisted neither. I went on their form link https://support.twitter.com/forms/platform and I checked the "I have an API policy question not covered by these points" option. They responded a few days after and asked me more information about the application and its app ID. I'm actually waiting for their answer.
EDIT:
So after several (a lot) emails with support#fabric.io and a few bugs I finally got whitelisted. But the option is currently unavailable with Fabric so you'll have to create a Twitter app on apps.twitter.com. Just send a mail with your app ID or your keys. They'll probably ask you a quick description of your app and it shouldn't take so much time to be whitelisted. Good luck!
After having a conversation with sdk-feedback#twitter.com, I got my App whitelisted. Here is the story:
Send mail to sdk-feedback#twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App. Mention in mail that you want to access user email address inside your App.
They will review your App and reply to you within 2-3 business days.
Once they say that your App is whitelisted, update your App's settings in Twitter Developer portal. Sign in to apps.twitter.com and:
On the 'Settings' tab, add a terms of service and privacy policy URL
On the 'Permissions' tab, change your token's scope to request email. This option will only been seen, once your App gets whitelisted.
It's time to code:
-(void)requestUserEmail
{
if ([[Twitter sharedInstance] session]) {
TWTRShareEmailViewController *shareEmailViewController =
[[TWTRShareEmailViewController alloc]
initWithCompletion:^(NSString *email, NSError *error) {
NSLog(#"Email %# | Error: %#", email, error);
}];
[self presentViewController:shareEmailViewController
animated:YES
completion:nil];
} else {
// Handle user not signed in (e.g. attempt to log in or show an alert)
}
}
Hope it helps !!!
Send email to sdk-feedback#twitter.com to whitelist your twitter login app first.
Swift 3.0 Code with fabric
#IBAction func btnTwitterAction(_ sender: AnyObject) {
Twitter.sharedInstance().logIn { (session, error) in
if session != nil {
print("signed in as \(session!.userName)");
let client = TWTRAPIClient.withCurrentUser()
let request = client.urlRequest(withMethod: "GET",
url: "https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true",
parameters: ["include_email": "true", "skip_status": "true"],
error: nil)
client.sendTwitterRequest(request) { response, data, connectionError in
if (connectionError == nil) {
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
print("Json response: ", json)
let firstName = json["name"]
let lastName = json["screen_name"]
let email = json["email"]
print("First name: ",firstName)
print("Last name: ",lastName)
print("Email: ",email)
} catch {
}
}
else {
print("Error: \(connectionError)")
}
}
} else {
NSLog("Login error: %#", error!.localizedDescription);
}
}
}
How to get email id in twitter ?
Step 1 : got to https://apps.twitter.com/app/
Step 2 : click on ur app > click on permission tab .
Step 3 : here check the email box
I've faced the same issue recently
Here is what you should try if you are using new twitter kit
Go to
https://apps.twitter.com/
Select permissions tab
Set it to Read Only
Code :
Twitter.sharedInstance().logIn(withMethods: [.webBased,.systemAccounts,.all]) {(session, error) -> Void in
if (session != nil) {
print("signed in as \(session?.userName)");
let client = TWTRAPIClient(userID: session?.userName)
client.loadUser(withID: (session?.userID)!, completion: { (user, error) in
let twitterClient = TWTRAPIClient.withCurrentUser()
let request = twitterClient.urlRequest(withMethod: "GET",
url: "https://api.twitter.com/1.1/account/verify_credentials.json",
parameters: ["include_email": "true", "skip_status": "true"],
error: nil)
twitterClient.sendTwitterRequest(request) { response, data, connectionError in
print(data!)
let s :String = String(data: data! as Data, encoding: String.Encoding.utf8)!
//
// let json = try JSONSerialization.jsonObject(with: responseData as Data, options: JSONSerialization.ReadingOptions.mutableLeaves) as? [String:AnyObject]
//
Twitter.sharedInstance().sessionStore.logOutUserID((session?.userID)!)
if let data = s.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
print(json!)
} catch {
print("Something went wrong")
}
}
}
})
} else {
}

Resources