How to fetch instagram app logged in user details in ios device using our application? - iphone

This is the first time I am working on Instagram API. If the user is already having instagram app in his device, how can we fetch his user details from our application?
Right now my app is redirecting to safari and asking the instagram credentials there though I have instagram app in my iPhone where I loggedin.
Can any one please help me with this?

We need Instagram.h and Instagram.m file to fetch instagram user details.
You need a create an application in the Instagram developer site to get app id.
instagram = [[Instagram alloc] initWithClientId:APP_ID delegate:nil];
NSString *const instagramUrlScheme = #"---YourAppName---";
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { //openo
if ([urlStr hasPrefix:instagramUrlScheme]) {
//[self showAlertWithTitle:THIS_METHOD message:url.description];
return [self.instagram handleOpenURL:url];
}
}
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
NSString *urlStr = url.description;
if ([urlStr hasPrefix:instagramUrlScheme]) {
return [self.instagram handleOpenURL:url];
}
return NO;
}
These are the instagram delegates you need to implement.
#pragma - IGSessionDelegate
-(void)igDidLogin
{
NSLog(#"Instagram did login");
//[[self appDelegate] showAlertWithTitle:#"igDidLogin" message:#""];
// here i can store accessToken
[[NSUserDefaults standardUserDefaults] setObject:[self appDelegate].instagram.accessToken forKey:#"accessToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
//NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"users/self/followed-by", #"method", nil];
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"users/self", #"method", nil];
[[self appDelegate].instagram requestWithParams:params
delegate:self];
}
-(void)igDidNotLogin:(BOOL)cancelled
{
NSLog(#"Instagram did not login");
NSString* message = nil;
if (cancelled) {
message = #"Access cancelled!";
}
else {
message = #"Access denied!";
}
UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:message
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
-(void)igDidLogout
{
NSLog(#"Instagram did logout");
// remove the accessToken
[[NSUserDefaults standardUserDefaults] setObject:nil forKey:#"accessToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
-(void)igSessionInvalidated
{
NSLog(#"Instagram session was invalidated");
}
You have to use these when you want to connect to instagram.
[self appDelegate].instagram.accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"accessToken"];
[self appDelegate].instagram.sessionDelegate = self;
[[self appDelegate].instagram logout];
[[self appDelegate].instagram authorize:[NSArray arrayWithObjects:#"comments", #"likes", nil]];
Hope this helps:

As far as my knowledge when we are redirecting from our app to other app we can't access the other app details (Login details).

As long as I also do know, this is not possible.
We can't get details of the other app from our app.
You can get more info for instagram by this instagram developer link.
Hope this helps you.

Related

how to check if already logged in Facebook in ios?

I am using "Graph Api" For Facebook login with in my app. I successfully logIn and logged out with this code
facebook = [[Facebook alloc] initWithAppId:kAppId andDelegate:self.viewController];
and i using below code for already facebook logged in
if (![facebook isSessionValid]) {
[facebook authorize:permissions ];
}
My problem is i install Facebook App, and i logged in via Facebook App. then i run my app, it ask again login Facebook. how i solve this issue. it should take as a default FB app login credentials. i saw many app using this feature. anyone know the solution
1. In your AppDelegate.m file
define NSString *const FBSessionStateChangedNotification =
#"com.example:FBSessionStateChangedNotification";
replace com.example with your bundle identifier name
2.- In method
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FBSession setActiveSession:[FBSession new]];
if ([FBSession activeSession].state == FBSessionStateCreatedTokenLoaded)
{
// means u are already logged in
//do ur code
[self openSessionWithAllowLoginUI:NO];
}
else
{ //do ur code
[self openSessionWithAllowLoginUI:YES];
}
}
3. whenenever and wherever this method is called after end of switch case write
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
[[NSNotificationCenter defaultCenter]
postNotificationName:FBSessionStateChangedNotification
object:session];
}
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI
{
return [FBSession openActiveSessionWithReadPermissions:#"email"
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session, FBSessionState state, NSError *error)
{
[self sessionStateChanged:session state:state error:error];
}];
}
Sorry in your appDelegate.h file it should be
extern NSString *const FBSessionStateChangedNotification;

Add Facebook SDK to my xCode project with Storyboard

I am following Getting Started with the Facebook SDK for iOS v3.1 to add Facebook SDK to my xCode project with Storyboard.
I did all the steps that described there.
We have a HelloFacebookSample in the Sample folder of Facebook SDK. it includes this code:
- (void)viewDidLoad {
[super viewDidLoad];
// Create Login View so that the app will be granted "status_update" permission.
FBLoginView *loginview = [[FBLoginView alloc] init];
loginview.frame = CGRectOffset(loginview.frame, 5, 5);
loginview.delegate = self;
[self.view addSubview:loginview];
[loginview sizeToFit];
}
// Post Status Update button handler; will attempt to invoke the native
// share dialog and, if that's unavailable, will post directly
- (IBAction)postStatusUpdateClick:(UIButton *)sender {
// Post a status update to the user's feed via the Graph API, and display an alert view
// with the results or an error.
NSString *name = self.loggedInUser.first_name;
NSString *message = [NSString stringWithFormat:#"Updating status for %# at %#",
name != nil ? name : #"me" , [NSDate date]];
// if it is available to us, we will post using the native dialog
BOOL displayedNativeDialog = [FBNativeDialogs presentShareDialogModallyFrom:self
initialText:nil
image:nil
url:nil
handler:nil];
if (!displayedNativeDialog) {
[self performPublishAction:^{
// otherwise fall back on a request for permissions and a direct post
[FBRequestConnection startForPostStatusUpdate:message
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:message result:result error:error];
self.buttonPostStatus.enabled = YES;
}];
self.buttonPostStatus.enabled = NO;
}];
}
}
Then sample works fine, but when I want to have it on my own project, I have this problem:
It is successfully added the FBLoginView to my self.view. but when I Login and then want to post something I just go to this page:
Finally I found the problem. I needed to add these codes to my AppDelegate:
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
// attempt to extract a token from the url
return [FBSession.activeSession handleOpenURL:url];
}
- (void)applicationWillTerminate:(UIApplication *)application {
// FBSample logic
// if the app is going away, we close the session object
[FBSession.activeSession close];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// FBSample logic
// We need to properly handle activation of the application with regards to SSO
// (e.g., returning from iOS 6.0 authorization dialog or from fast app switching).
[FBSession.activeSession handleDidBecomeActive];
}
They were not described in the link. It could be better to let the new users know about these details.

Facebook SDK + iPhone SDK + SSO

I know that this question has been asked, but I have been reading through threads all day and have applied all of the fixes I could find and am still having an issue.
I am trying to implement Facebook SDK's new SSO feature to allow my app to authenticate with Facebook's app instead of a webView. When my app switches to Facebook's app, it says loading for a few seconds and switches back but the token is still null. I have a feeling it has to do with the URL scheme for my app but I have followed many tutorials and am fairly confident that my current plist values are correct:
Here is the code I have implemented in my appDelegate and viewController files:
appDelegate.h
Facebook *facebook;
appDelegate.m
// Pre 4.2 support
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
return [facebook handleOpenURL:url];
}
// For 4.2+ support
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [facebook handleOpenURL:url];
}
SecondViewController.m
-(IBAction) fbButton {
//FACEBOOK INTEGRATION
appDelegate.facebook = [[Facebook alloc] initWithAppId:#"222087841143437" andDelegate:appDelegate];
// Check and retrieve authorization information
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"]
&& [defaults objectForKey:#"FBExpirationDateKey"]) {
appDelegate.facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
appDelegate.facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
if (![appDelegate.facebook isSessionValid]) {
appDelegate.facebook.sessionDelegate = self;
[appDelegate.facebook authorize:permissions];
NSLog(#"Token: %#", [defaults objectForKey:#"FBAccessTokenKey"]);
} else {
NSLog(#"Already logged in!");
}
[appDelegate.facebook requestWithGraphPath:#"me" andDelegate:self];
}
- (void)request:(FBRequest *)request didLoad:(id)result {
NSString *nameID = [[NSString alloc] initWithFormat:#"%# (%#)", [result objectForKey:#"name"], [result objectForKey:#"id"]];
NSMutableArray *userData = [[NSMutableArray alloc] initWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
[result objectForKey:#"id"], #"id",
nameID, #"name",
[result objectForKey:#"picture"], #"details",
nil], nil];
[userData release];
[nameID release];
NSLog(#"DATA RECEIVED: %#", result);
}
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
NSLog(#"request:didReceiveResponse:");
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(#"%#", [error localizedDescription]);
NSLog(#"Err details: %#", [error description]);
};
- (void)fbDidLogin {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[[appDelegate facebook] accessToken] forKey:#"FBAccessTokenKey"];
[defaults setObject:[[appDelegate facebook] expirationDate] forKey:#"FBExpirationDateKey"];
[defaults synchronize];
NSLog(#"Facebook Logged in!");
[appDelegate.facebook requestWithGraphPath:#"me" andDelegate:self];
}
I know that I call [appDelegate.facebook requestWithGraphPath:#"me" andDelegate:self] twice, but I don't think that's the problem.
Here is a snippet from the console when I press the login button:
2011-10-18 15:37:33.287 Track[2235:707] Token: (null)
2011-10-18 15:37:36.578 Track[2235:707] request:didReceiveResponse:
2011-10-18 15:37:36.584 Track[2235:707] The operation couldn’t be completed. (facebookErrDomain error 10000.)
2011-10-18 15:37:36.586 Track[2235:707] Err details: Error Domain=facebookErrDomain Code=10000 "The operation couldn’t be completed. (facebookErrDomain error 10000.)" UserInfo=0x1ce480 {error=<CFBasicHash 0x1c9560 [0x3e368630]>{type = mutable dict, count = 2,
entries =>
2 : <CFString 0x19a830 [0x3e368630]>{contents = "type"} = <CFString 0x11d230 [0x3e368630]>{contents = "OAuthException"}
3 : <CFString 0x1f5b60 [0x3e368630]>{contents = "message"} = <CFString 0x1f8a70 [0x3e368630]>{contents = "An active access token must be used to query information about the current user."}
I appreciate the help and I really hope I didn't miss a discussion on here that solves this problem. Here are a few (of the many) that I have read through and had no success in finding a solution
How to implement Single Sign On (SSO) using facebook ios sdk for iphone
Facebook SSO and request iOS SDK
Facebook API for iPhone Error: An active access token must be used
Make sure that your Facebook application (the actual application that you created on Facebook) is not in sandbox mode and if it is make sure that the user your Facebook application (the iPhone Facebook client) is currently logged in with is a developer for that application.

facebook dialog failing silently when not called immediately after authorize

I have the following function to post to Facebook using the latest iOS Facebook SDK.
-(void)fbPost:(NSMutableDictionary *) params{
NSLog(#"fbPost called");
if (![facebook isSessionValid]) {
NSLog(#"session invalid, calling fblogin");
[self fblogin];
}
if ([facebook isSessionValid]) {
NSLog(#"session valid, calling publishToFB");
[self.facebook dialog:#"stream.publish" andParams:params andDelegate:self];
}
}
It works fine when there is no existing session: it logs in to facebook, gets permissions, returns to the app, shows the dialog and publishes the status. However, when trying a second time, isSessionValid returns true the first time and nothing happens, although the log shows publishToFB is called.
The session is persisted in fbDidLogin:
[[NSUserDefaults standardUserDefaults] setObject:self.facebook.accessToken forKey:#"AccessToken"];
[[NSUserDefaults standardUserDefaults] setObject:self.facebook.expirationDate forKey:#"ExpirationDate"];
[[NSUserDefaults standardUserDefaults] synchronize];
and loaded in application didFinishLaunchingWithOptions:
facebook.accessToken = [[NSUserDefaults standardUserDefaults] stringForKey:#"AccessToken"];
facebook.expirationDate = (NSDate *) [[NSUserDefaults standardUserDefaults] objectForKey:#"ExpirationDate"];
I made sure to ask for offline_access permission when logging in:
_permissions = [[NSArray arrayWithObjects:
#"publish_stream",#"offline_access",nil] retain];
It appears the problem was in drawing the dialog in this code in FBDialog.m
UIWindow* window = [UIApplication sharedApplication].keyWindow;
if (!window) {
window = [[UIApplication sharedApplication].windows objectAtIndex:0];
}
If I comment out the If clause, it works OK. I guess that in my app setup, "keyWindow" is not front-most, so the dialog was not showing up.

To display permission page in facebook of iphone

I am new to iphone development, i want to display the permission page after logging facebook.
buttonIndex is the index of my actionsheets.
if(buttonIndex == 1)
{
session = [FBSession sessionForApplication:#"My App key" secret:#"My Key" delegate:self];
FBLoginDialog* dialog = [[[FBLoginDialog alloc] initWithSession:session] autorelease];
[dialog show];
}
by using those code successfully loggin to facebook, but i want to permission page to display,
so i can use,
- (void)session:(FBSession*)session didLogin:(FBUID)uid
{
NSLog(#"User with id %lld logged in.", uid);
FBPermissionDialog* dialog1 = [[[FBPermissionDialog alloc] init] autorelease];
dialog1.delegate = self;
dialog1.permission = #"uid";
[dialog1 show];
}
But its not working. Where can i put that code.
And I want to share my content after the permission allowed.
If i logout the facebook, it goes to the browser but i want to return my application after logout,
Please help me out, guide me plz.
I would change this dialog1.permission = #"uid"; to something like this
dialog1.permission = #"publish_stream";. Because you want to publish your content to the users stream, right?
- (void)session:(FBSession*)session didLogin:(FBUID)uid
After loggin in I would first check if you might already have the permission to publish to the user's stream, by creating a FBRequest
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: #"publish_stream", #"ext_perm", nil];
[[FBRequest requestWithDelegate:self] call:#"facebook.users.hasAppPermission" params:params];
The result you can evaluate here
- (void)request:(FBRequest*)request didLoad:(id)result
e.g. like this
if ([request.method isEqualToString:#"facebook.users.hasAppPermission"])
{
NSString *success = result;
if ([success isEqualToString:#"1"])
{
NSLog(#"User has app permission");
// publish content now
...
}
else
{ // else ask for permission, opening permission dialog
...
}
I highly recommend this guy's tutorial, Brandon Treb, on integrating Facebook. He does a very thorough presentation and takes you line-by-line, so if it does not work, its a typo on your part. His tutorial got me up and running in less than two hours.
http://brandontreb.com/