Идентификатор пользователя Twitter в iOS 5
Я использую следующий код, чтобы получить информацию о пользователе из Twitter в iOS 5.
if ([TWTweetComposeViewController canSendTweet])
{
// Create account store, followed by a Twitter account identifer
account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
// Request access from the user to use their Twitter accounts.
[account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
{
// Did user allow us access?
if (granted == YES)
{
// Populate array with all available Twitter accounts
arrayOfAccounts = [account accountsWithAccountType:accountType];
[arrayOfAccounts retain];
// Populate the tableview
if ([arrayOfAccounts count] > 0)
[self performSelectorOnMainThread:@selector(updateTableview) withObject:NULL waitUntilDone:NO];
}
}];
}
//
-(void)updateTableview
{
numberOfTwitterAccounts = [arrayOfAccounts count];
NSLog(@"Twiter details-- %@",[arrayOfAccounts objectAtIndex:0]);
}
В моей консоли NSLog
я получаю вывод следующим образом:
Twiter details-- type:com.apple.twitter
identifier: E8591841-2AE0-4FC3-8ED8-F286BE7A36B0
accountDescription: @Sadoo55
username: [email protected]
objectID: x-coredata://F8059811-CFB2-4E20-BD88-F4D06A43EF11/Account/p8
enabledDataclasses: {(
)}
properties: {
"user_id" = 308905856;
}
parentAccount: (null)
owningBundleID:com.apple.Preferences
Я хочу получить "user_id" от этого. Как я могу получить "user_id" (т.е. 308905856)?
Ответы
Ответ 1
Получение идентификатора пользователя и/или имени пользователя намного проще.
версия iOS 7
ACAccount *account = accountsArray[0];
NSString *userID = ((NSDictionary*)[account valueForKey:@"properties"])[@"user_id"];
или
ACAccount *twitterAccount = accountsArray[0];
NSRange range = [account.description rangeOfString:@" [0-9]{7,8}"
options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
NSString *userID = [[account.description substringWithRange:range] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"User ID: %@", userID);
}
версия iOS 5
Был найден недокументированный метод ACAccount с именем accountProperties типа NSDictionary с ключом user_id.
![ACAccount properties]()
ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
NSString *userID = [[twitterAccount accountProperties] objectForKey:@"user_id"];
NSString *username = twitterAccount.username;
** Не работает в iOS6, потому что метод больше не определен.
Ответ 2
Вот что я сделал, чтобы получить user_id в iOS5 и iOS6.
NSDictionary *tempDict = [[NSMutableDictionary alloc] initWithDictionary:
[twitterAccount dictionaryWithValuesForKeys:[NSArray arrayWithObject:@"properties"]]];
NSString *tempUserID = [[tempDict objectForKey:@"properties"] objectForKey:@"user_id"];
Ответ 3
Вы можете считать объект учетной записи, как словарь, и выполнить это:
ACAccount *account = [twitterAccounts objectAtIndex:0];
NSString *userID = [account valueForKeyPath:@"properties.user_id"];
Это вернет user_id
Ответ 4
Я думаю, проблема в потоке вашего кодирования. Повторите проверку с помощью приведенных ниже ссылок.
Ошибка, похоже, является более связанной с каркасом ошибкой.
Я бы предложил вам пройти следующий учебник, который я нашел лучше всего в Интернете:
http://iosdevelopertips.com/core-services/ios-5-twitter-framework-part-1.html
Плюс, этот тоже потрясающий, с большим количеством деталей и упрощенным объяснением от Рэя.
Я следую его блогу за то же самое.
http://www.raywenderlich.com/5519/beginning-twitter-in-ios-5