How to get twitter profile pic using api 1.1 from iOS?

为君一笑 提交于 2019-12-21 23:12:39

问题


I am using MGTwitterEngine lib to authenticate Twitter account, but after successful login I want to get user profile pic but not able to get it and following method is stopped working:

https://api.twitter.com/1.1/users/profile_image?screen_name=username&size=bigger

I just tried above method but no success. Then I have did lot of research on it and I finally got following api to get user profile information which include profile pic:

https://api.twitter.com/1.1/users/show.json?screen_name=username

But this api requires authentication by passing Authorization in Request header which I was not able to generate.

Here is my code which I have tried:

here authdata is the string which I am getting back from MGTwitterEngine lib after successful login.

NSString *authData = [[NSUserDefaults standardUserDefaults] valueForKey:@"authData"];
NSString *subAuthdata = [authData substringFromIndex:[authData rangeOfString:@"oauth_token_secret="].location];
subAuthdata = [subAuthdata substringToIndex:[subAuthdata rangeOfString:@"&user_id="].location];
NSLog(@"%@", subAuthdata);

NSLog(@"encoded: %@", [self base64Encode:subAuthdata]);

NSString *accessTokenHeaderToPost = [NSString stringWithFormat:@"Basic %@", [self base64Encode:subAuthdata]];

NSString  *twitURL = @"https://api.twitter.com/1.1/users/show.json?screen_name=username";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString: twitURL]];
[request setHTTPMethod:@"GET"];
[request setValue:accessTokenHeaderToPost forHTTPHeaderField:@"Authorization"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

NSLog (@"RESP: %@", responseString);

But it always says Bad authentication data.

Please help me on this...


回答1:


Here is a solution using STTwitter:

STTwitterAPI *twitter = [STTwitterAPI twitterAPIAppOnlyWithConsumerKey:@"" consumerSecret:@""];

[twitter verifyCredentialsWithSuccessBlock:^(NSString *bearerToken) {

    [twitter getUsersShowForUserID:nil orScreenName:@"barackobama" includeEntities:nil successBlock:^(NSDictionary *user) {

        NSString *profileImageURLString = [user valueForKey:@"profile_image_url"];
        NSURL *url = [NSURL URLWithString:profileImageURLString];
        UIImage *profileImage = [UIImage imageWithContentsOfURL:url];

    } errorBlock:^(NSError *error) {
        //
    }];

} errorBlock:^(NSError *error) {
    //
}];


来源:https://stackoverflow.com/questions/17996676/how-to-get-twitter-profile-pic-using-api-1-1-from-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!