ios - request_token - twitter python api




獲取推特朋友列表? (2)

因為這個 friends / list api需要身份驗證才能獲取好友列表。

我在twitter friends / list API中收到了 Bad Authentication data 響應。 登錄時我收到用戶ID,屏幕名稱,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中發送的必需參數是什麼。 在本文檔中,他們給出的所有參數都是可選的 https://developer.twitter.com/en/docs/accounts-and-users/follow-search-get-users/api-reference/get-friends-list


在Swift 4.2,Xcode 10.1和iOS 12.1中

最後我得到了解決方案。 首先我們需要授權然後需要實現朋友列表api。

Pure Swift代碼不可用。 但我實施的是純粹的快速。

如果你想從twitter獲取 好友/列表 數據,你需要使用 兩個API

1)oauth2 / token API

2)好友/列表API

oauth2 / token api中,您可以獲得訪問令牌,因為您需要訪問令牌以獲取朋友列表。 而且您需要 用戶ID,屏幕名稱

但在這裡你 必須記住 一個重點。

1)首先使用 oauth2 / token api作為訪問令牌。

2)獲取訪問令牌後,使用 twitter登錄 api獲取 用戶ID和屏幕名稱。

3)現在使用 friends / list api。

首先,如果您使用 twitter登錄,然後 使用 oauth2 / token api訪問令牌 ,則可能會出現 Bad Authentication數據 錯誤。 所以,請按順序執行以上3個步驟。

1)獲取訪問令牌代碼(oauth2 / token api):

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()
}

輸出:

{"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAA............xqT3t8T"}

2)使用推特代碼登錄

@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))");
        }
    }

}

輸出:

在這裡,您將獲得userName,userId,authtoken,authTokenSecret,屏幕名稱和電子郵件等。

3)現在從friends / list api獲取好友列表 。 在這裡你可以得到朋友/列表,用戶/查找,關注者/ ids,粉絲/列表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()

        }
    }

}

此代碼在任何地方都不可用。 我為這段代碼做了很多嘗試,我花了很多時間。 謝謝。





twitter-oauth