【问题标题】:How to get twitter profile picture in ios?如何在ios中获取推特头像?
【发布时间】:2013-09-25 21:27:08
【问题描述】:

我写了以下代码:

NSURL *url = [NSURL URLWithString:@"http://api.twitter.com/1.1/users/show.json"];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:username, @"screen_name" ,[[controller.engine accessToken] secret]];

TWRequest *request = [[TWRequest alloc] initWithURL:url parameters:params requestMethod:TWRequestMethodGET];

[request performRequestWithHandler:
 ^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
     if (responseData) {
         NSDictionary *user = [NSJSONSerialization JSONObjectWithData:responseData
                                         options:NSJSONReadingAllowFragments
                                           error:NULL];

         NSString *profileImageUrl = [user objectForKey:@"profile_image_url"];

         NSLog(@"%@",profileImageUrl);
     }
 }];

但我总是会收到 Bad authentication 错误。我觉得我错过了什么。有人请检查我的代码吗?或者提供任何关于检索 twitter 用户个人资料图片的建议?

谢谢

【问题讨论】:

  • @Romit 查看我的回答

标签: ios authentication twitter


【解决方案1】:

您是否考虑过为此使用第 3 方 Twitter 引擎?我使用FHSTwitterEngine 取得了相当大的成功,而且它似乎正在积极开发中。

要提取个人资料图片,您可以执行以下操作:

[[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:@"<consumer_key>" andSecret:@"<consumer_secret>"];
[[FHSTwitterEngine sharedEngine]showOAuthLoginControllerFromViewController:self
withCompletion:^(BOOL success) {
    if (success) {
        UIImage *profileImg = [[FHSTwitterEngine sharedEngine] getProfileImageForUsername:@"<username>" andSize:size];
    }
}];

【讨论】:

    【解决方案2】:

    这是我过去尝试过的

    [PFTwitterUtils logInWithBlock:^(PFUser *user, NSError *error) {
        if (!user) {
            NSLog(@"Uh oh. The user cancelled the Twitter login.");
            [[NSNotificationCenter defaultCenter] postNotificationName:notificationUserLoginFailed
                                                                object:error];
            return;
        } else {
    
            // TODO find a way to fetch details with Twitter..
    
            NSString * requestString = [NSString stringWithFormat:@"https://api.twitter.com/1.1/users/show.json?screen_name=%@", user.username];
    
    
            NSURL *verify = [NSURL URLWithString:requestString];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:verify];
            [[PFTwitterUtils twitter] signRequest:request];
            NSURLResponse *response = nil;
            NSData *data = [NSURLConnection sendSynchronousRequest:request
                                                 returningResponse:&response
                                                             error:&error];
    
    
            if ( error == nil){
                NSDictionary* result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
                _NSLog(@"%@",result);
    
                [user setObject:[result objectForKey:@"profile_image_url_https"]
                         forKey:@"picture"];
                // does this thign help?
                [user setUsername:[result objectForKey:@"screen_name"]];
    
                NSString * names = [result objectForKey:@"name"];
                NSMutableArray * array = [NSMutableArray arrayWithArray:[names componentsSeparatedByString:@" "]];
                if ( array.count > 1){
                    [user setObject:[array lastObject]
                             forKey:@"last_name"];
    
                    [array removeLastObject];
                    [user setObject:[array componentsJoinedByString:@" " ]
                             forKey:@"first_name"];
                }
    
                [user saveInBackground];
            }
    
            [[NSNotificationCenter defaultCenter] postNotificationName:notificationUserDidLogin
                                                                object:nil];
    
            return;
        }
    
    
    
    }];
    

    【讨论】:

    • Abhijit 感谢您的回复,但我不想制作任何依赖应用程序。 Parse 是第三方框架。你还有其他选择吗?
    【解决方案3】:

    请注意,您应该登录您的 iOS 设备才能使用此功能:

    - (void)signIniwthTwitter
    {
       if ([TWTweetComposeViewController canSendTweet])
        {
    
    
                // Set up the built-in twitter composition view controller.
            TWTweetComposeViewController *tweetViewController = [[TWTweetComposeViewController alloc] init];
    
    
                // Create the completion handler block.
            [tweetViewController setCompletionHandler:^(TWTweetComposeViewControllerResult result) {
                [self dismissModalViewControllerAnimated:YES];
    
            }];
    
                // Present the tweet composition view controller modally.
            [self presentModalViewController:tweetViewController animated:YES];
    
        }
        else
        {
                    [self getTwitterAccountDetails];
        }
    
    
    
    }
    
    
    - (void) getTwitterAccountDetails
    {
    
        [DejalBezelActivityView activityViewForView:self.navigationController.navigationBar.superview];
    
        self.view.userInteractionEnabled  = NO;
        self.connectionstatusLabel.text = @"Getting user details....";
            // Create an account store object.
        ACAccountStore *accountStore = [[ACAccountStore alloc] init];
    
            // Create an account type that ensures Twitter accounts are retrieved.
        ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    
            // Request access from the user to use their Twitter accounts.
        [accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
        #pragma unused (error)
            if(granted) {
                    // Get the list of Twitter accounts.
                NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
    
                    // For the sake of brevity, we'll assume there is only one Twitter account present.
                    // You would ideally ask the user which account they want to tweet from, if there is more than one Twitter account present.
                if ([accountsArray count] > 0) {
                        // Grab the initial Twitter account to tweet from.
                    ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
                    NSLog(@"Account details %@",twitterAccount);
                    _userid = [[twitterAccount valueForKey:@"properties"] valueForKey:@"user_id"];
                    _screenName = [twitterAccount valueForKey:@"username"];
                    NSLog(@"user id %@",_userid);
                    [self getProfileDetailsFromTwitter];
    
                }
            }
        }];
    }
    
    - (void) getProfileDetailsFromTwitter
    {
            self.connectionstatusLabel.text = @"Getting user profile details....";
    
        NSURL *twitterURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://api.twitter.com/1/users/show.json?user_id=%@&include_entities=true",_userid]];
        TWRequest *postRequest = [[TWRequest alloc] initWithURL:twitterURL parameters:nil requestMethod:TWRequestMethodGET];
    
            // Perform the request created above and create a handler block to handle the response.
        [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
            NSString *output;
    
            if ([urlResponse statusCode] == 200) {
                    // Parse the responseData, which we asked to be in JSON format for this request, into an NSDictionary using NSJSONSerialization.
                NSError *jsonParsingError = nil;
                NSDictionary *publicTimeline = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonParsingError];
    
                NSLog(@"Twiiter Profile Deatils %@",publicTimeline);
                _twitterUserProfileDetails = [[MobileYakUser alloc]init];
                _twitterUserProfileDetails.firstName = [publicTimeline objectForKey:@"name"];
                _twitterUserProfileDetails.lastName = [publicTimeline objectForKey:@"name"];
    
    
                output = [NSString stringWithFormat:@"HTTP response status: %i\nPublic timeline:\n%@", [urlResponse statusCode], publicTimeline];
                NSURL *url =
                [NSURL URLWithString:@"http://api.twitter.com/1/users/profile_image/"];
    
                NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
                [params setValue:_screenName forKey:@"screen_name"];
                [params setValue:@"original" forKey:@"size"];
    
                TWRequest *request = [[TWRequest alloc] initWithURL:url
                                                         parameters:params
                                                      requestMethod:TWRequestMethodGET];
    
                [request performRequestWithHandler:
                 ^(NSData *imageresponseData, NSHTTPURLResponse *imageFetchurlResponse, NSError *imageerror) {
    #pragma unused (imageFetchurlResponse,imageerror)
                     if (imageresponseData) {
                             self.connectionstatusLabel.text = @"Getting user profile image....";
                         UIImage *image = [UIImage imageWithData:imageresponseData];
                         _twitterUserProfileDetails.profileImage = image;
                         self.connectionstatusLabel.text = @"Please fill up following fields for login";
                         self.view.userInteractionEnabled = YES;
                         [DejalActivityView removeView];
                     }
                 }];
            }
            else {
                output = [NSString stringWithFormat:@"HTTP response status: %i\n", [urlResponse statusCode]];
            }
    
        }];
    }
    

    【讨论】:

    • 我试过这段代码在模拟器中运行。它应该在模拟器上工作吗?
    • 转到 twitter 并在模拟器中登录 twitter 凭据
    • 好的,但我只需要通过我的应用程序登录。用户不应该离开应用程序进行 Twitter 登录。
    • 模拟器可能无法使用此功能,因为没有活动的 Twitter 帐户可以登录
    【解决方案4】:

    //Twitter Fetch Data for Methods for ios using block https://www.dropbox.com/sh/vdxtw3x1coyyj8x/AADw6cyYNjeHM-77GqAyBZ5oa?dl=0

    【讨论】:

      【解决方案5】:

      这是 profile_image_url_https ;)

      我们可以在不使用 Twitter sdk 的情况下访问个人资料图片。在 iOS 中使用 Social framework 我们可以使用它。

      我使用 ACAccounts 而不是 Twitter IOS SDK 的 MGTwitterEngine 等...... 将使用 iPhone 设置中提供的 Twitter 帐户。

              if(!accountStore)
                  accountStore = [[ACAccountStore alloc] init];
              ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
      
              [accountStore
               requestAccessToAccountsWithType:accountType
               options:NULL
               completion:^(BOOL granted, NSError *error) {
                   if (granted) {
                       //  Step 2:  Create a request
                       NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
                       self.twitterAccount = [accountsArray objectAtIndex:0];
                       // NSString *userID = [[twitterAccount valueForKey:@"properties"] valueForKey:@"user_id"];
      
                       NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/users/show.json"];
                       NSDictionary *params = @{@"screen_name" : twitterAccount.username
                                                };
                       SLRequest *request =
                       [SLRequest requestForServiceType:SLServiceTypeTwitter
                                          requestMethod:SLRequestMethodGET
                                                    URL:url
                                             parameters:params];
      
                       //  Attach an account to the request
                       [request setAccount:[accountsArray lastObject]];
      
                       //  Step 3:  Execute the request
                       [request performRequestWithHandler:^(NSData *responseData,
                                                            NSHTTPURLResponse *urlResponse,
                                                            NSError *error) {
                           if (responseData) {
      
                               if (urlResponse.statusCode >= 200 && urlResponse.statusCode < 300) {
                                   [self performSelectorOnMainThread:@selector(twitterdetails:)
                                                          withObject:responseData waitUntilDone:YES];
                               }
                               else {
      
                                   NSLog(@"The response status code is %d", urlResponse.statusCode);
                               }
                           }
                       }];
                   }
                   else
                   {
                       dispatch_async(dispatch_get_main_queue(), ^{
                           [self dismissError:@"Please set up your twitter account in iphone settings"];
      
                       });
                   }
               }];
      
      
      
      -(void)twitterdetails:(NSData *)responseData {
      
          NSError* error = nil;
          NSDictionary* json = [NSJSONSerialization
                                JSONObjectWithData:responseData //1
                                options:NSJSONReadingAllowFragments
                                error:&error];
      
          NSString *name = [json objectForKey:@"name"];
          NSString *scrnm = [json objectForKey:@"screen_name"];
          NSString *twitterid = [json objectForKey:@"id"];
          NSString *prof_img = [json objectForKey:@"profile_image_url"];
          NSString *location = [json objectForKey:@"location"];
      }
      

      【讨论】:

      • 我知道响应字典中的这个变量,但我没有收到 Twitter 响应。我如何得到回应?你有什么例子吗?
      【解决方案6】:

      试试这个,它是使用fabricSDK获取用户配置文件的最新版本

        -(void)usersShow:(NSString *)userID
      {
          NSString *statusesShowEndpoint = @"https://api.twitter.com/1.1/users/show.json";
          NSDictionary *params = @{@"user_id": userID};
      
          NSError *clientError;
          NSURLRequest *request = [[[Twitter sharedInstance] APIClient]
                                   URLRequestWithMethod:@"GET"
                                   URL:statusesShowEndpoint
                                   parameters:params
                                   error:&clientError];
      
          if (request) {
              [[[Twitter sharedInstance] APIClient]
               sendTwitterRequest:request
               completion:^(NSURLResponse *response,
                            NSData *data,
                            NSError *connectionError) {
                   if (data) {
                       // handle the response data e.g.
                       NSError *jsonError;
                       NSDictionary *json = [NSJSONSerialization
                                             JSONObjectWithData:data
                                             options:0
                                             error:&jsonError];
      
                       NSLog(@"%@",[json description]);
                   }
                   else {
                       NSLog(@"Error code: %ld | Error description: %@", (long)[connectionError code], [connectionError localizedDescription]);
                   }
               }];
          }
          else {
              NSLog(@"Error: %@", clientError);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-07-18
        • 2020-04-27
        • 2011-01-08
        • 1970-01-01
        • 2021-04-23
        • 2016-04-03
        • 2012-07-01
        • 2018-07-14
        • 1970-01-01
        相关资源
        最近更新 更多