I am a beginner in iOS. I am trying to create an app and referred a lot of posts in the stackoverflow and some other sites and i used the following code to access the Facebook account.
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
[appDelegate.session closeAndClearTokenInformation];
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
appDelegate.session = [[FBSession alloc] init];
}
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
}];
}
After that in a function i used the following code to access the Facebook details of the user.
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
_FirstName.text = user.first_name;
regisrationdetails.fbid = user.id;
_LastName.text=user.last_name;
_EmailAddress.text=user.email;
NSArray *locationarray=[[NSArray alloc]initWithObjects:user.location,nil];
_City.text=[locationarray objectAtIndex:1];
NSLog(#"%#",user.first_name);
}
}];
No error is being shown but i can't get the information from Facebook the the text fields.If anyone good at this knows how to access the information then please help me out.
- (IBAction)getMeButtonTapped:(id)sender {
if(!_accountStore)
_accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookTypeAccount = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[_accountStore requestAccessToAccountsWithType:facebookTypeAccount
options:#{ACFacebookAppIdKey: #"571438296262222", ACFacebookPermissionsKey: #[#"email"]}
completion:^(BOOL granted, NSError *error) {
if(granted){
NSArray *accounts = [_accountStore accountsWithAccountType:facebookTypeAccount];
_facebookAccount = [accounts lastObject];
NSLog(#"Success");
[self me];
}else{
// ouch
NSLog(#"Fail");
NSLog(#"Error: %#", [error localizedDescription]);
}
}];
}
- (void)me
{
NSURL *meurl = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *merequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:meurl
parameters:nil];
merequest.account = _facebookAccount;
[merequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *meDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", meDataString);
}];}
Use this hope this helps you, also add social framework as well as Accounts Framework
try this..
- (void)fetchFacebookUserInfo {
if ( FBSession.activeSession.isOpen) {
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error) {
if (!error) {
NSString *name = user.name;
NSString *userName = user.username;
NSString *firstName = user.first_name;
NSString *lastName = user.last_name;
NSString *email1 = [user objectForKey:#"email"];
NSString *birthday1 = user.birthday;
NSString *locale = [user objectForKey:#"locale"];
NSString *location = [user.location objectForKey:#"name"];
}
}];
}
Related
Im getting Facebook User Data to auto completing signup textfields.
Problem: I did a test and NSLog returns information quickly, but to update the TextFields.text it's delaying.
Code:
- (IBAction)facebookProfile:(id)sender {
if(!_accountStore)
_accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookTypeAccount = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[_accountStore requestAccessToAccountsWithType:facebookTypeAccount
options:#{ACFacebookAppIdKey: #"417425124162461", ACFacebookPermissionsKey: #[#"email"]}
completion:^(BOOL granted, NSError *error) {
if(granted){
NSArray *accounts = [_accountStore accountsWithAccountType:facebookTypeAccount];
_facebookAccount = [accounts lastObject];
NSLog(#"Success");
[self me];
}else{
// ouch
NSLog(#"Fail");
NSLog(#"Error: %#", error);
}
}];
}
- (void)me {
NSURL *meUrl = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *meRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodGET URL:meUrl parameters:nil];
meRequest.account = _facebookAccount;
[meRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (!error) {
NSDictionary *resultsDictionary = [responseData objectFromJSONData];
NSLog(#"%#", [resultsDictionary objectForKey:#"name"]);
// The problem is here. While NSLog runs in seconds showing Facebook User Name, the textfiend.text updates take about 10 seconds longer.
_tfName.text = [resultsDictionary objectForKey:#"name"];
_tfEmail.text = [resultsDictionary objectForKey:#"email"];
_tfGender.text = [resultsDictionary objectForKey:#"gender"];
_tfBirthday.text = [resultsDictionary objectForKey:#"birthday"];
}
}];
}
You need to perform UI updates on the main thread. Your completion handler is being called on a background thread.
[meRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (!error) {
NSDictionary *resultsDictionary = [responseData objectFromJSONData];
NSLog(#"%#", [resultsDictionary objectForKey:#"name"]);
// The problem is here. While NSLog runs in seconds showing Facebook User Name, the textfiend.text updates take about 10 seconds longer.
// Ensure UI updated on main queue
dispatch_async(dispatch_get_main_queue(), ^{
_tfName.text = [resultsDictionary objectForKey:#"name"];
_tfEmail.text = [resultsDictionary objectForKey:#"email"];
_tfGender.text = [resultsDictionary objectForKey:#"gender"];
_tfBirthday.text = [resultsDictionary objectForKey:#"birthday"];
});
}
}];
I have updated the version for the graph Api to v2. Now the issue I am facing is,when I executed the following code It shows me empty array :
FBRequest *friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *result, NSError *error) {
NSArray *friendshipid;
NSString *username;
if (!error) {
NSLog(#"friends = %#", [result description]);
}
if (completion) {
completion(friendshipid, username, error);
}
}];
}
}
I got to know that facebook sdk had some changes for the user friends and now It has to take the permission for the user_friends, but I have no idea where to make changes to ask for Permission for user_friends
You can use the given code snippet. Here, i have used the Classes of Social Framework to get the Facebook friends. Hope it will work for you.
- (void) connectWithFacebookFriends
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountTypeFacebook = [accountStore accountTypeWithAccountTypeIdentifier:
ACAccountTypeIdentifierFacebook];
NSDictionary *options = #{ACFacebookAppIdKey: kFaceBookId,
ACFacebookPermissionsKey: #[#"user_friends"],
ACFacebookAudienceKey: ACFacebookAudienceFriends
};
[accountStore requestAccessToAccountsWithType:accountTypeFacebook
options:options
completion:^(BOOL granted, NSError *error)
{
if(granted) {
NSArray *accounts = [accountStore
accountsWithAccountType:accountTypeFacebook];
ACAccount* facebookAccount = [accounts lastObject];
NSString *acessToken = [NSString stringWithFormat:#"%#",facebookAccount.credential.oauthToken];
NSDictionary *parameters = #{#"access_token": acessToken};
NSURL *feedURL = [NSURL URLWithString:#"https://graph.facebook.com/me/friends"];
SLRequest *feedRequest =
[SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:feedURL
parameters:parameters];
[feedRequest performRequestWithHandler:^(NSData *responseData,
NSHTTPURLResponse *urlResponse, NSError *error)
{
NSString * str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
DLog(#"%#",str);
NSLog(#"Request failed, %#", [urlResponse description]);
}];
} else {
NSLog(#"Access Denied");
NSLog(#"[%#]",[error localizedDescription]);
}
}];
}
I am making a test app through that I want to post a video on facebook. I am using latest sdk of facebook. But I am not able to post it on facebook. The video is coming from web service.
How to convert video url in nsdata and mu code is below
NSString *astrUserid=[[mutTimeline objectAtIndex:indexpath] objectForKey:#"user_id"];
NSString *astrImageid=[[mutTimeline objectAtIndex:indexpath] objectForKey:#"image_id"];
NSString *astrExt=[[mutTimeline objectAtIndex:indexpath] objectForKey:#"ext"];
NSString *aStrDisplyimage=[NSString stringWithFormat:#"http://followme.pmcommu.com/audio/user/%#-%#.%#",astrUserid, astrImageid,astrExt ];
NSURL *aimageurl=[NSURL URLWithString:aStrDisplyimage];
NSString *filePathOfVideo = [aimageurl path];
NSLog(#"Path Of Video is %#", filePathOfVideo);
NSData *videoData = [NSData dataWithContentsOfFile:filePathOfVideo];
//you can use dataWithContentsOfURL if you have a Url of video file
//NSData *videoData = [NSData dataWithContentsOfURL:shareURL];
//NSLog(#"data is :%#",videoData);
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#"Video name ", #"name",
#"description of Video", #"description",
nil];
if (FBSession.activeSession.isOpen)
{
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error)
{
NSLog(#"RESULT: %#", result);
//[self throwAlertWithTitle:#"Success" message:#"Video uploaded"];
}
else
{
NSLog(#"ERROR: %#", error.localizedDescription);
//[self throwAlertWithTitle:#"Denied" message:#"Try Again"];
}
}];
}
else
{
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_actions",
nil];
// OPEN Session!
[FBSession openActiveSessionWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceEveryone allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (error)
{
NSLog(#"Login fail :%#",error);
}
else if (FB_ISSESSIONOPENWITHSTATE(status))
{
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error)
{
//[self throwAlertWithTitle:#"Success" message:#"Video uploaded"];
NSLog(#"RESULT: %#", result);
}
else
{
//[self throwAlertWithTitle:#"Denied" message:#"Try Again"];
NSLog(#"ERROR: %#", error.localizedDescription);
}
}];
}
}];
}
I am new for that can any one help me please
or this will help you for upload and streaming video, i think
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
// Specify App ID and permissions
NSDictionary *options = #{ACFacebookAppIdKey: FACEBOOK_ID,
ACFacebookPermissionsKey: #[#"publish_stream", #"video_upload"],
ACFacebookAudienceKey: ACFacebookAudienceFriends}; // basic read permissions
[accountStore requestAccessToAccountsWithType:facebookAccountType options:options completion:^(BOOL granted, NSError *e) {
if (granted) {
NSArray *accountsArray = [accountStore accountsWithAccountType:facebookAccountType];
if ([accountsArray count] > 0) {
ACAccount *facebookAccount = [accountsArray objectAtIndex:0];
NSDictionary *parameters = #{#"description": aMessage};
SLRequest *facebookRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:[NSURL URLWithString:#"https://graph.facebook.com/me/videos"]
parameters:parameters];
[facebookRequest addMultipartData: aVideo
withName:#"source"
type:#"video/mp4"
filename:#"video.mov"];
facebookRequest.account = facebookAccount;
[facebookRequest performRequestWithHandler:^(NSData* responseData, NSHTTPURLResponse* urlResponse, NSError* error) {
if (error == nil) {
NSLog(#"responedata:%#", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
}else{
NSLog(#"%#",error.description);
}
}];
}
} else {
NSLog(#"Access Denied");
NSLog(#"[%#]",[e localizedDescription]);
}
}];
Get the publish permission
NSArray* permissions = [[NSArray alloc] initWithObjects:
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
[permissions release];
Try this
- (void)fbDidLogin {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"mov"];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#"Video Test Title", #"title",
#"Video Test Description", #"description",
nil];
[facebook requestWithGraphPath:#"me/videos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}
try this
[NSData dataWithContentsOfURL:[NSURL URLWithString:#"Your URL"]]
-(void)facbookSharng {
NSLog(#"Permission for sharing..%#",[FBSDKAccessToken currentAccessToken].permissions);
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"contact_email"])
{
FBSDKShareVideo *ShareVideo = [FBSDKShareVideo videoWithVideoURL:appDelegateObj.finalVideoUrl];
ShareVideo.videoURL = appDelegateObj.finalVideoUrl;
FBSDKShareVideoContent *ShareContnt = [[FBSDKShareVideoContent alloc] init];
ShareContnt.video = ShareVideo;
[FBSDKShareAPI shareWithContent:ShareContnt delegate:self]
// write the deleate methdo for post ID..
}
This my method to send new score:
-(void)sendScore :(int) score : (NSString *)uID : (ACAccount *)ac{
NSString *url =[NSString stringWithFormat:#"https://graph.facebook.com/%#/scores",uID];
NSURL * strURL =[NSURL URLWithString:url];
NSDictionary * parameter =#{#"score": #"10000"};
SLRequest * request =[SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST URL:strURL parameters:parameter];
request.account = _accFB;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (!error) {
NSLog(#"Error: %#",error);
NSString * str = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str: %#",str);
}
}];
}
When run , it show error:
{
"message":"(#200) Requires extended permission: publish_actions",
"type":"OAuthException",
"code":200
}
How I can add publish_actions ?
You can request additional permissions for an active session at any time. Facebook recommends that you ask for permissions when your app actually needs them to complete an action initiated by the user. Also note that you cannot add read and write permissions together.
Here's the code to request for publish_actions publish permissions for an active session-
FB iOS SDK
[FBSession.activeSession requestNewPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
__block NSString *alertText;
__block NSString *alertTitle;
if (!error) {
if ([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound){
// Permission not granted, tell the user we will not publish
alertTitle = #"Permission not granted";
alertText = #"Your action will not be published to Facebook.";
[[[UIAlertView alloc] initWithTitle:title
message:text
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil] show];
} else {
// Permission granted, publish the OG story
[self publishStory];
}
} else {
// There was an error, handle it
// See https://developers.facebook.com/docs/ios/errors/
}
}];
Social Framework
-(void)requestPermissions
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
__block ACAccount *facebookAccount = nil;
ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
// Specify App ID and permissions
NSDictionary *options = #{
ACFacebookAppIdKey: #"MYAPPID",
// READ permissions here (if any)
ACFacebookPermissionsKey: #[#"email"],
ACFacebookAudienceKey: ACFacebookAudienceFriends
};
[accountStore requestAccessToAccountsWithType:facebookAccountType
options:options completion:^(BOOL granted, NSError *e)
{
if (granted) {
NSDictionary *options2 = #{
ACFacebookAppIdKey: #"MYAPPID",
// PUBLISH permissions here
ACFacebookPermissionsKey: #[#"publish_actions"],
ACFacebookAudienceKey: ACFacebookAudienceFriends
};
[accountStore requestAccessToAccountsWithType:facebookAccountType options:options2 completion:^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [accountStore accountsWithAccountType:facebookAccountType];
facebookAccount = [accounts lastObject];
}
else {
NSLog(#"Access denied 2");
NSLog(#"%#", [error description]);
}
}];
} else {
NSLog(#"Error: %#", [e description]);
NSLog(#"Access denied");
}
}];
}
This is the first time i am trying to integrate Facebook into my ios app.
I am trying to import first name, last name and some other details from Facebook. I am able to log in to Facebook but i cannot import the details. I think my code is wrong somewhere and i don't know where!
if (appDelegate.session.isOpen) {
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error2) {
regdet.firstname = user.first_name;
regdet.lastname = user.last_name;
regdet.email = [user objectForKey:#"email"];
regdet.address1 = [user objectForKey:#"locale"];
regdet.city = [user.location objectForKey:#"name"];
NSLog(#"firstname %#",regdet.firstname);
}];
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
// Create a new, logged out session.
appDelegate.session = [[FBSession alloc] init];
}
// if the session isn't open, let's open it now and present the login UX to the user
[appDelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error1) {
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error2) {
regdet.firstname = user.first_name;
regdet.lastname = user.last_name;
regdet.email = [user objectForKey:#"email"];
regdet.address1 = [user objectForKey:#"locale"];
regdet.city = [user.location objectForKey:#"name"];
NSLog(#"firstname %#",regdet.firstname);
}];
[self performSegueWithIdentifier: #"Facebooksegue" sender: self];
}];
}
Try this
FBLoginView *loginView=[[FBLoginView alloc]init];
loginView.delegate=self;
loginView.readPermissions = #[#"first_name",
#"last_name",
#"location",
#"id",
#"access_token",
#"email"];
NSArray* permissions = [NSArray arrayWithObjects: #"email", nil];
loginView.readPermissions = #[#"email"];
loginView.readPermissions=permissions;
{
[FBSession openActiveSessionWithReadPermissions:Nil allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user1,
NSError *error)
{
if (!error)
{
firstname=user1.first_name;
lastname=user1.last_name;
city=[user1.location objectForKey:#"name"];
email=user1[#"email"];
fbid=user1.id;
[[NSUserDefaults standardUserDefaults]setObject:Loggedin forKey:#"token"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
NSURL *url = [[NSURL alloc]initWithString:[NSString stringWithFormat:#"%#action=currfbuser&email=%#&fb_id=%#",MainURL,email,fbid ]];
NSError *errors;
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *json = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errors];
NSString *status = json[#"status"];
user = json[#"user"];
if ([status isEqualToString:#"success"])
{
[self performSegueWithIdentifier: #"LogIN" sender: self];
}
else if (!([fbid isEqualToString:#""]))
{
[self performSegueWithIdentifier: #"Facebooksegue" sender: self];
}
NSLog(#"%#",firstname);
NSLog(#"%#",lastname);
NSLog(#"%#",city);
NSLog(#"%#",email);
NSLog(#"%#",fbid);
}];}];
}
Here is Facebook documentation and example. You need to ask for additional permission.
[FBSession openActiveSessionWithReadPermissions:#[#"basic_info", #"email"]
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// Respond to session state changes,
// ex: updating the view
}];
Here is Facebook permission keys and description