How to get user details using twitter api v1.1 (Twitter error 215)
Asked Answered
T

2

10

I have used the twitter api provided by twitter,to get the details but not able to execute it, even tried to pass the authentication data like consumer secret key, consumer key, token but the result is same.
I am able to login and receiving twitter authentication token but not able to get user details. Below code is used by me (I am using MGtwitter engine) :

NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://api.twitter.com/1.1/users/show.json?screen_name=%@",username]]];

NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];

NSString *returnString = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
    NSError *err = nil;

twitterLogin = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

Error is shown as below:

errors = (
{
    code = 215;
    message = "Bad Authentication data";
} );
Twirp answered 13/6, 2013 at 6:58 Comment(5)
I have seen on developer twitter website that they have updated their api from yesterdayJeffries
seriously man i am also getting same error from last day..Buprestid
Maybe related: from dev.twitter.com: In version 1.1, we're requiring applications to authenticate all of their requests with OAuth 1.0a or Application-only authentication.Headgear
I have tried to send the authentication parameters but still getting the same response ( token,consumer secret key,consumer key and even replaced the username by the id)Twirp
i don't know why people like @khan post such a comment that they need to removed it afterwards.Capful
X
15

First, you need to Authenticate your request (Get permission).

second, see follow these steps:

1.Download FHSTwitterEngine Twitter Library.

2.Add the folder FHSTwitterEngine" to your project and #import "FHSTwitterEngine.h".

3.add SystemConfiguration.framework to your project.

Usage : 1.in the [ViewDidLoad] add the following code.

UIButton *logIn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    logIn.frame = CGRectMake(100, 100, 100, 100);
    [logIn setTitle:@"Login" forState:UIControlStateNormal];
    [logIn addTarget:self action:@selector(showLoginWindow:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:logIn];

[[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:@"<consumer_key>" andSecret:@"<consumer_secret>"];
    [[FHSTwitterEngine sharedEngine]setDelegate:self];

and don't forget to import the delegate FHSTwitterEngineAccessTokenDelegate.

  1. you need to get the permission for your request, with the following method which will present Login window:
- (void)showLoginWindow:(id)sender {
    [[FHSTwitterEngine sharedEngine]showOAuthLoginControllerFromViewController:self withCompletion:^(BOOL success) {
        NSLog(success?@"L0L success":@"O noes!!! Loggen faylur!!!");
    }];
}

when the Login window is presented, enter your Twitter Username and Password to authenticate your request.

  1. add the following methods to your code:
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[FHSTwitterEngine sharedEngine]loadAccessToken];
    NSString *username = [[FHSTwitterEngine sharedEngine]loggedInUsername];// self.engine.loggedInUsername;
    if (username.length > 0) {
        lbl.text = [NSString stringWithFormat:@"Logged in as %@",username];
        [self listResults];


    } else {
        lbl.text = @"You are not logged in.";
    }

}
- (void)storeAccessToken:(NSString *)accessToken {
    [[NSUserDefaults standardUserDefaults]setObject:accessToken forKey:@"SavedAccessHTTPBody"];
}

- (NSString *)loadAccessToken {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SavedAccessHTTPBody"];
}

4.Now you are ready to get your request, with the following method(in this method I created a Twitter search for some Hashtag, to get the screen_name for example):

- (void)listResults {

    dispatch_async(GCDBackgroundThread, ^{
        @autoreleasepool {
            [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

        // the following line contains a FHSTwitterEngine method wich do the search.

            dict = [[FHSTwitterEngine sharedEngine]searchTweetsWithQuery:@"#iOS" count:100 resultType:FHSTwitterEngineResultTypeRecent unil:nil sinceID:nil maxID:nil];
          // NSLog(@"%@",dict);
            NSArray *results = [dict objectForKey:@"statuses"];

          //  NSLog(@"array text = %@",results);
            for (NSDictionary *item in results) {
                NSLog(@"text == %@",[item objectForKey:@"text"]);
                NSLog(@"name == %@",[[item objectForKey:@"user"]objectForKey:@"name"]);
                NSLog(@"screen name == %@",[[item objectForKey:@"user"]objectForKey:@"screen_name"]);
                NSLog(@"pic == %@",[[item objectForKey:@"user"]objectForKey:@"profile_image_url_https"]);
            }

            dispatch_sync(GCDMainThread, ^{
                @autoreleasepool {
                    UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"Complete!" message:@"Your list of followers has been fetched" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [av show];
                    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                }
            });
        }
    });
}

That's all. I just got the screen_name from a search Query, you can get a timeline for a user using the following methods:

// statuses/user_timeline
- (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count;
- (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count sinceID:(NSString *)sinceID maxID:(NSString *)maxID; 

instead of the search method above.

Note: see the FHSTwitterEngine.h to know what method you need to use. Note: to get the <consumer_key> and the <consumer_secret> you need to to visit this link to register your app in Twitter.

Xenogenesis answered 13/6, 2013 at 9:29 Comment(3)
I found out the way of getting all other detail, but the prior requirement is user detail so that i could register the user in my own database, please let me know the exact method among several to fulfil the requirement.Twirp
Yes got the way towards success ... it works brother, just modified the getProfileImageForUsername function. Stay connected for sharing and receiving.Twirp
@RavirajPeerbitsII may be you need getProfileImageForUsername method to get name,id,screename,followers,retweet .. all possible data except email..Buprestid
T
0

Got the solution after MKAlatrash revert, to get the user profile follow certain steps in the code as under :

[[FHSTwitterEngine sharedEngine]getProfileImageForUsername:username andSize:FHSTwitterEngineImageSizeNormal];

jump to definition of this function and replace the if ... else if part

if ([userShowReturn isKindOfClass:[NSError class]]) {
        return [NSError errorWithDomain:[(NSError *)userShowReturn domain] code:[(NSError *)userShowReturn code] userInfo:[NSDictionary dictionaryWithObject:request forKey:@"request"]];
        NSLog(@"user show return %@",userShowReturn);
    } else if ([userShowReturn isKindOfClass:[NSDictionary class]]) {
        return userShowReturn;
        NSString *url = [userShowReturn objectForKey:@"profile_image_url"]; // normal

        if (size == 0) { // mini
            url = [url stringByReplacingOccurrencesOfString:@"_normal" withString:@"_mini"];
        } else if (size == 2) { // bigger
            url = [url stringByReplacingOccurrencesOfString:@"_normal" withString:@"_bigger"];
        } else if (size == 3) { // original
            url = [url stringByReplacingOccurrencesOfString:@"_normal" withString:@""];
        }

        id ret = [self sendRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];

        if ([ret isKindOfClass:[NSData class]]) {
            return [UIImage imageWithData:(NSData *)ret];
        }

        return ret;
    }

That really was helpful thanks

Twirp answered 13/6, 2013 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.