我正在使用适用于 iOS 5 的 Twitter 和 Accounts Framework。问题是我无法使用http://api.twitter.com/1/friends/ids.json?screen_name=%@ “这个 api获取朋友列表.但是从twitter api explorer,我得到了朋友列表。(twitter explorer api = https://dev.twitter.com/console)。
2 回答
我正在使用适用于 iOS 的 Twitter 原生框架。
要从 Twitter 获取好友列表,您可以这样做(四个步骤)。
- 将 Twitter 和 Accounts Framework 添加到项目中。
- 获取当前 Twitter 帐户实例。
- 然后您将通过 API Request 从 Twitter 获取好友 ID 列表。
- 最后,您可以通过 ID 获取好友名称或其他数据并放入 Array
所以...您的 .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;
你的 .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);
}];
}
如果您对此有任何疑问,请告诉我!!很高兴能帮助你!
在 Swift 4.2、Xcode 10.1 和 iOS 12.1 中
如果您想从 twitter 获取好友/列表数据,您需要使用两个 API。
1) oauth2/令牌 API
2) 好友/列表 API
在oauth2/token api 中,您可以获得访问令牌,因为您需要好友列表的访问令牌。你需要用户 id, screen name。
但是在这里你必须记住一个重要的点。
1) 首先使用oauth2/token api 获取访问令牌。
2) 获取访问令牌后,使用twitter login api 获取用户 ID 和屏幕名称。
3) 现在使用friends/list api。
首先,如果您使用twitter 登录,然后使用 oauth2/token api 访问令牌,您可能会遇到Bad Authentication data错误。因此,请按顺序执行上述 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))");
}
}
}
输出:
在这里,您将获得用户名、用户 ID、authtoken、authTokenSecret、屏幕名称和电子邮件等。
3) 现在从 friends/list 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()
}
}
}
此代码在任何地方均不可用。我为这段代码做了很多尝试,为此我花了很多时间。谢谢你。