Ios 想在iPhone应用程序中显示twitter好友列表吗

Ios 想在iPhone应用程序中显示twitter好友列表吗,ios,objective-c,iphone,Ios,Objective C,Iphone,我正在使用iOS5的Twitter和帐户框架。 问题是,我无法使用“此api”获取好友列表。但从twitter api资源管理器中,我获取了好友列表。(twitter资源管理器api=)。我使用的是用于iOS的twitter原生框架 要从Twitter获取好友列表,您可以这样做(四个步骤) 将Twitter和帐户框架添加到项目中 获取当前Twitter帐户实例 然后您将通过API从Twitter获得好友ID列表 请求 最后,您可以通过ID和 排列 所以…你的.h文件应该是这样的 #import

我正在使用iOS5的Twitter和帐户框架。
问题是,我无法使用“此api”获取好友列表。但从twitter api资源管理器中,我获取了好友列表。(twitter资源管理器api=)。

我使用的是用于iOS的twitter原生框架

要从Twitter获取好友列表,您可以这样做(四个步骤)

  • 将Twitter和帐户框架添加到项目中
  • 获取当前Twitter帐户实例
  • 然后您将通过API从Twitter获得好友ID列表 请求
  • 最后,您可以通过ID和 排列
  • 所以…你的.h文件应该是这样的

    #import <UIKit/UIKit.h>
    #import <Twitter/Twitter.h>
    #import <Accounts/Accounts.h>
    
    @interface LoginView : UIViewController{    
    
        ACAccount *myAccount;  
        NSMutableString *paramString;  
        NSMutableArray *resultFollowersNameList;
    }
    
    @property(nonatomic,retain) ACAccount *myAccount;
    @property(nonatomic, retain) NSMutableString *paramString;
    @property(nonatomic, retain) NSMutableArray *resultFollowersNameList;
    
    #导入
    #进口
    #进口
    @接口LoginView:UIViewController{
    账户*我的账户;
    NSMutableString*参数字符串;
    NSMUTABLEARRY*resultFollowersNameList;
    }
    @财产(非原子,保留)账户*我的账户;
    @属性(非原子,保留)NSMutableString*paramString;
    @属性(非原子,保留)NSMutableArray*resultFollowersNameList;
    
    你的.m文件应该是这样的

    Get The Twitter Account Instance
    /******To check whether More then Twitter Accounts setup on device or not *****/
    
    -(void)getTwitterAccounts {
    
        ACAccountStore *accountStore = [[ACAccountStore alloc] init];    
        ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];   
        [accountStore requestAccessToAccountsWithType:accountType
                                withCompletionHandler:^(BOOL granted, NSError *error) {
    
        if (granted && !error) {
            accountsList = [accountStore accountsWithAccountType:accountType]; 
    
            int NoOfAccounts = [accountsList count]; 
    
            if (NoOfAccounts > 1) {      
    
                NSLog(@"device has more then one twitter accounts %i",NoOfAccounts);
    
            } 
            else 
            {
                myAccount = [accountsList objectAtIndex:0];             
                NSLog(@"device has single twitter account : 0");           
    
            }
        } 
        else 
        {
            // show alert with information that the user has not granted your app access, etc.
        }                                
    
      }];
    }
    
    
    /************* getting followers/friends ID list code start here *******/
    // so far we have instnce of current account, that is myAccount //
    
    -(void) getTwitterFriendsIDListForThisAccount{
    
        /*** url for all friends *****/
        // NSURL *url = [NSURL URLWithString:@"http://api.twitter.com/1/friends/ids.json"]; 
    
        /*** url for Followers only ****/
        NSURL *url = [NSURL URLWithString:@"http://api.twitter.com/1/followers/ids.json"]; 
    
        NSDictionary *p = [NSDictionary dictionaryWithObjectsAndKeys:myAccount.username, @"screen_name", nil];
    
        TWRequest *twitterRequest = [[TWRequest alloc] initWithURL:url parameters:p requestMethod:TWRequestMethodGET];
        [twitterRequest setAccount:myAccount];
        [twitterRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResposnse, NSError *error)
         {
             if (error) {
    
             }
             NSError *jsonError = nil;
             // Convert the response into a dictionary
             NSDictionary *twitterFriends = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONWritingPrettyPrinted error:&jsonError];         
    
             NSArray *IDlist = [twitterFriends objectForKey:@"ids"];
    
             NSLog(@"response value is: %@", IDlist);        
    
             int count = IDlist.count;         
             for (int i=0; i<count; i++ ) {    
    
    
                 [paramString appendFormat:@"%@",[IDlist objectAtIndex:i]];             
    
                 if (i <count-1) {
                     NSString *delimeter = @",";
                     [paramString appendString:delimeter];
                 }
    
             }
    
             NSLog(@"The mutable string is %@", paramString);
             [self getFollowerNameFromID:paramString];
         }
         ];
    
    }
    
    
    -(void) getFollowerNameFromID:(NSString *)ID{
    
    
        NSURL *url = [NSURL URLWithString:@"http://api.twitter.com/1/users/lookup.json"];
        NSDictionary *p = [NSDictionary dictionaryWithObjectsAndKeys:ID, @"user_id",nil];
        NSLog(@"make a request for ID %@",p);
    
        TWRequest *twitterRequest = [[TWRequest alloc] initWithURL:url
                                                        parameters:p
                                                     requestMethod:TWRequestMethodGET];    
       [twitterRequest setAccount:myAccount];
    
    
        [twitterRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
            if (error) {
    
            }
            NSError *jsonError = nil;       
    
    
            NSDictionary *friendsdata = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONWritingPrettyPrinted error:&jsonError];
         //  NSLog(@"friendsdata value is %@", friendsdata);
    
    
         //  resultFollowersNameList = [[NSArray alloc]init];
           resultFollowersNameList = [friendsdata valueForKey:@"name"];
            NSLog(@"resultNameList value is %@", resultFollowersNameList);
    
    
        }];        
    
    }
    
    获取Twitter帐户实例
    /******检查是否在设备上设置了超过Twitter的帐户*****/
    -(void)getWitterAccounts{
    ACAccountStore*accountStore=[[ACAccountStore alloc]init];
    ACAccountType*accountType=[accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierWitter];
    [accountStore requestAccessToAccountsWithType:accountType
    withCompletionHandler:^(已授予布尔,N错误*错误){
    如果(已授予&&!错误){
    accountsList=[accountStore accountsWithAccountType:accountType];
    int NoOfAccounts=[accountslistcount];
    如果(NoOfAccounts>1){
    NSLog(@“设备有多个twitter帐户%i”,NoOfAccounts);
    } 
    其他的
    {
    myAccount=[accountsList对象索引:0];
    NSLog(@“设备有一个twitter帐户:0”);
    }
    } 
    其他的
    {
    //显示带有用户未授予您的应用程序访问权限等信息的警报。
    }                                
    }];
    }
    /*************获取追随者/朋友ID列表代码从这里开始*******/
    //到目前为止,我们没有往来账户,那就是我的账户//
    -(void)此帐户的GetWitterFriendsIDList{
    /***所有朋友的url*****/
    //NSURL*url=[NSURL URLWithString:@”http://api.twitter.com/1/friends/ids.json"]; 
    /***仅适用于关注者的url****/
    NSURL*url=[NSURL URLWithString:@”http://api.twitter.com/1/followers/ids.json"]; 
    NSDictionary*p=[NSDictionary Dictionary WithObjectsAndKeys:myAccount.username,@“screen_name”,nil];
    TWRequest*twitterRequest=[[TWRequest alloc]initWithURL:url参数:p requestMethod:TWRequestMethodGET];
    [TwitterRequestSetAccount:myAccount];
    [TwitterRequestPerformRequestWithHandler:^(NSData*responseData,NSHTTPURLRResponse*URResponse,NSError*错误)
    {
    如果(错误){
    }
    n错误*jsonError=nil;
    //将响应转换为字典
    NSDictionary*twitterFriends=[NSJSONSerialization JSONObject WithData:responseData选项:NSJSONWriting预打印错误:&jsonError];
    NSArray*IDlist=[twitterFriends objectForKey:@“ids”];
    NSLog(@“响应值为:%@”,IDlist);
    int count=IDlist.count;
    
    对于Swift 4.2、Xcode 10.1和iOS 12.1中的(int i=0;i)

    如果你想从twitter上获取好友/列表数据,你需要使用两个API

    1)oauth2/tokenAPI

    2)好友/列表API

    oauth2/tokenapi中,您可以获得访问令牌,因为您需要朋友列表的访问令牌。并且您需要用户id、屏幕名称

    但在这里,你必须记住一个要点

    1) 首先对访问令牌使用oauth2/token
    api

    2) 获取访问令牌后,使用推特登录用户id和屏幕名称的api。

    3) 现在使用friends/listapi

    首先,如果您使用twitter登录,然后使用oauth2/token api访问token,您可能会得到类似错误的身份验证数据

    1)获取访问令牌代码(oauth2/tokenAPI):

    func getAccessToken() {
    
        //RFC encoding of ConsumerKey and ConsumerSecretKey
        let encodedConsumerKeyString:String = "sx5r...S9QRw".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
        let encodedConsumerSecretKeyString:String = "KpaSpSt.....tZVGhY".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
        print(encodedConsumerKeyString)
        print(encodedConsumerSecretKeyString)
        //Combine both encodedConsumerKeyString & encodedConsumerSecretKeyString with " : "
        let combinedString = encodedConsumerKeyString+":"+encodedConsumerSecretKeyString
        print(combinedString)
        //Base64 encoding
        let data = combinedString.data(using: .utf8)
        let encodingString = "Basic "+(data?.base64EncodedString())!
        print(encodingString)
        //Create URL request
        var request = URLRequest(url: URL(string: "https://api.twitter.com/oauth2/token")!)
        request.httpMethod = "POST"
        request.setValue(encodingString, forHTTPHeaderField: "Authorization")
        request.setValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
        let bodyData = "grant_type=client_credentials".data(using: .utf8)!
        request.setValue("\(bodyData.count)", forHTTPHeaderField: "Content-Length")
        request.httpBody = bodyData
    
        let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
            }
    
            let responseString = String(data: data, encoding: .utf8)
            let dictionary = data
            print("dictionary = \(dictionary)")
            print("responseString = \(String(describing: responseString!))")
    
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }
    
            do {
                let response = try JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>
                print("Access Token response : \(response)")
                print(response["access_token"]!)
                self.accessToken = response["access_token"] as! String
    
                self.getStatusesUserTimeline(accessToken:self.accessToken)
    
            } catch let error as NSError {
                print(error)
            }
        }
    
        task.resume()
    }
    
    2)使用twitter代码登录

    @IBAction func onClickTwitterSignin(_ sender: UIButton) {
    
        //Login and get session
        TWTRTwitter.sharedInstance().logIn { (session, error) in
    
            if (session != nil) {
                //Read data
                let name = session?.userName ?? ""
                print(name)
                print(session?.userID  ?? "")
                print(session?.authToken  ?? "")
                print(session?.authTokenSecret  ?? "")
    
                 // self.loadFollowers(userid: session?.userID ?? "")
    
                //Get user email id
                let client = TWTRAPIClient.withCurrentUser()
                client.requestEmail { email, error in
                    if (email != nil) {
                        let recivedEmailID = email ?? ""
                        print(recivedEmailID)
                    } else {
                        print("error--: \(String(describing: error?.localizedDescription))");
                    }
                }
                //Get user profile image url's and screen name
                let twitterClient = TWTRAPIClient(userID: session?.userID)
                twitterClient.loadUser(withID: session?.userID ?? "") { (user, error) in
                    print(user?.profileImageURL ?? "")
                    print(user?.profileImageLargeURL ?? "")
                    print(user?.screenName ?? "")
                }
    
    
    
                let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
                self.navigationController?.pushViewController(storyboard, animated: true)
            } else {
                print("error: \(String(describing: error?.localizedDescription))");
            }
        }
    
    }
    
    输出:

    func getAccessToken() {
    
        //RFC encoding of ConsumerKey and ConsumerSecretKey
        let encodedConsumerKeyString:String = "sx5r...S9QRw".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
        let encodedConsumerSecretKeyString:String = "KpaSpSt.....tZVGhY".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!
        print(encodedConsumerKeyString)
        print(encodedConsumerSecretKeyString)
        //Combine both encodedConsumerKeyString & encodedConsumerSecretKeyString with " : "
        let combinedString = encodedConsumerKeyString+":"+encodedConsumerSecretKeyString
        print(combinedString)
        //Base64 encoding
        let data = combinedString.data(using: .utf8)
        let encodingString = "Basic "+(data?.base64EncodedString())!
        print(encodingString)
        //Create URL request
        var request = URLRequest(url: URL(string: "https://api.twitter.com/oauth2/token")!)
        request.httpMethod = "POST"
        request.setValue(encodingString, forHTTPHeaderField: "Authorization")
        request.setValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
        let bodyData = "grant_type=client_credentials".data(using: .utf8)!
        request.setValue("\(bodyData.count)", forHTTPHeaderField: "Content-Length")
        request.httpBody = bodyData
    
        let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
            }
    
            let responseString = String(data: data, encoding: .utf8)
            let dictionary = data
            print("dictionary = \(dictionary)")
            print("responseString = \(String(describing: responseString!))")
    
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }
    
            do {
                let response = try JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any>
                print("Access Token response : \(response)")
                print(response["access_token"]!)
                self.accessToken = response["access_token"] as! String
    
                self.getStatusesUserTimeline(accessToken:self.accessToken)
    
            } catch let error as NSError {
                print(error)
            }
        }
    
        task.resume()
    }
    
    在这里您将获得用户名、用户ID、authtoken、authTokenSecret、屏幕名和电子邮件等

    3)现在从friends/list api获取好友列表。在这里,您可以获取friends/list、users/lookup、followers/ID、followers/list api的数据等

    func getStatusesUserTimeline(accessToken:String) {
    
        let userId = "109....456"
        let twitterClient = TWTRAPIClient(userID: userId)
        twitterClient.loadUser(withID: userId) { (user, error) in
            if user != nil {
                //Get users timeline tweets
                var request = URLRequest(url: URL(string: "https://api.twitter.com/1.1/friends/list.json?screen_name=KS....80&count=10")!) //users/lookup, followers/ids, followers/list 
                request.httpMethod = "GET"
                request.setValue("Bearer "+accessToken, forHTTPHeaderField: "Authorization")
    
                let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
                    print("error=\(String(describing: error))")
                    return
                    }
    
          //                    let responseString = String(data: data, encoding: .utf8)
          //                    let dictionary = data
          //                    print("dictionary = \(dictionary)")
          //                    print("responseString = \(String(describing: responseString!))")
    
                    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
                        print("statusCode should be 200, but is \(httpStatus.statusCode)")
                        print("response = \(String(describing: response))")
                    }
    
                    do {
                        let response = try JSONSerialization.jsonObject(with: data, options: [])
                        print(response)
    
                    } catch let error as NSError {
                        print(error)
                    }
                }
    
                task.resume()
    
            }
        }
    
    }
    

    此代码在任何地方都不可用。我为此代码做了很多尝试,并为此花费了很多时间。谢谢。

    请始终记住,在询问之前请先尝试,如果您能将您的问题代码张贴在您遇到问题的地方,那么您会尽快得到更多答案,这样会更好。。希望您能找到我!@Tapanathvani我的荣幸。。顺便说一句,如果我的答案有帮助的话你让他们把绿色记号标记为已接受的答案。回答得好,我需要知道如何发布推特,你能帮我吗please@RDC所有结果显示我为空,请提供任何链接或此示例应用程序。