Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 获取twitter好友列表?_Ios_Swift_Twitter_Oauth_Twitter Oauth - Fatal编程技术网

Ios 获取twitter好友列表?

Ios 获取twitter好友列表?,ios,swift,twitter,oauth,twitter-oauth,Ios,Swift,Twitter,Oauth,Twitter Oauth,我在twitter好友/列表API中得到了错误的身份验证数据响应。登录时,我会获得用户名、屏幕名、authToken和authTokenSecret func loadFollowers(userid:String) { //let twapi = "https://api.twitter.com/1.1/followers/list.json?cursor=-1&user_id=\(session)&count=5000" let twapi = "https

我在twitter好友/列表API中得到了
错误的身份验证数据
响应。登录时,我会获得用户名、屏幕名、authToken和authTokenSecret

func loadFollowers(userid:String) {

    //let twapi = "https://api.twitter.com/1.1/followers/list.json?cursor=-1&user_id=\(session)&count=5000"
    let twapi = "https://api.twitter.com/1.1/friends/list.json?cursor=-1&user_id=\(userid)&count=10"
    let url2 = URL(string: twapi)!
    print(url2)
    URLSession.shared.dataTask(with: url2, completionHandler: { (data, response, error) in

    //UIApplication.shared.isNetworkActivityIndicatorVisible = false
        do {
            let userData = try JSONSerialization.jsonObject(with: data!, options:[])
            print(userData)
        } catch {
            NSLog("Account Information could not be loaded \(error)")
        }
    }).resume()
}
输出:

{
"errors": [
    {
        "code": 215,
        "message": "Bad Authentication data."
    }
]
}
friends/list.json
API中需要发送哪些参数。 在本文档中,所有参数都是可选的。

因为此好友/listapi需要身份验证才能获取好友列表。

在Swift 4.2、Xcode 10.1和iOS 12.1中

我终于找到了解决办法。在这里,我们首先需要授权,然后需要实现好友列表api

纯Swift代码不可用。但我是用纯swift实现的

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

1)oauth2/tokenAPI

2)好友/列表API

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

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

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

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

3) 现在使用friends/listapi

首先,如果您使用twitter登录,然后使用oauth2/token api访问令牌,您可能会得到类似错误的身份验证数据。因此,请按照上述3个步骤进行操作

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)现在从好友/列表api获取好友列表。在这里,您可以获得好友/列表、用户/查找、关注者/ID、关注者/列表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()

        }
    }

}

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

请发送身份验证api及其所需参数。请告诉我朋友/列表API所需参数列表。谢谢你,这个密码就像一个符咒。但是为了获得下一个用户列表和下一个用户/朋友列表,它会给我一个未授权的错误,比如:{error=“not authorized.”request=“/1.1/friends/list.json”}知道为什么它没有授权吗?