Проблема интеграции Twitter с ACAccountStore (iOS 5)

Когда я запускаю код ниже с iOS 6.0, он работает

ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

[account requestAccessToAccountsWithType:accountType options:nil
                                  completion:^(BOOL granted, NSError *error)
     {
         dispatch_async(dispatch_get_main_queue(), ^{

             if (granted) 
             {
                 //MY CODE
             }
         });

     }];

и когда я запускаю этот код с iOS 5.0 или 5.1, происходит сбой со следующим выводом:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: '-[ACAccountStore requestAccessToAccountsWithType:options:completion:]: 
unrecognized selector sent to instance 0x68a57c0'

Не знаю об этом странном журнале сбоев ..

Подскажите пожалуйста, как избавиться от этого..


person Mehul Mistri    schedule 06.03.2013    source источник
comment
У меня такая же проблема, как вам удалось от нее избавиться..! Пожалуйста помоги..!   -  person JgdGuy    schedule 22.08.2013
comment
Об этом есть хорошая презентация на WWDC 2012: adcdownload.apple.com/wwdc_2012/w2_session_20   -  person iwasrobbed    schedule 18.09.2013


Ответы (4)


Используйте метод ниже:

[account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
 {

   if (granted) {

            //Your code
            }
        }
   }];
person yen    schedule 06.03.2013

Это немного поздно, но причина, по которой вы получаете эту ошибку, заключается в том, что requestAccessToAccountsWithType:options:completion: является новым в iOS 6.

В iOS 5 и более ранних версиях вместо этого используйте метод requestAccessToAccountsWithType:withCompletionHandler (этот метод устарел в iOS 6).

См. документы: https://developer.apple.com/library/ios/documentation/Accounts/Reference/ACAccountStoreClassRef/Reference/Reference.html#//apple_ref/doc/uid/TP40011021-CH1-SW12

person Jeremy Wiebe    schedule 05.09.2013

Попробуйте обновить для этого:

ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

// iOS 6
if ( [account respondsToSelector:@selector(requestAccessToAccountsWithType: options: completion:)] )
{
[account requestAccessToAccountsWithType:accountType options:nil
                                  completion:^(BOOL granted, NSError *error)
     {
         dispatch_async(dispatch_get_main_queue(), ^{

             if (granted) 
             {
                 //MY CODE
             }
         });

     }];
}

// iOS 5
else if ( [account respondsToSelector:@selector(requestAccessToAccountsWithType: withCompletionHandler:)] )
{
[account requestAccessToAccountsWithType:accountType
                                  withCompletionHandler:^(BOOL granted, NSError *error)
     {
         dispatch_async(dispatch_get_main_queue(), ^{

             if (granted) 
             {
                 //MY CODE
             }
         });

     }];
}
else
{
// iOS 4 or less
}
person CReaTuS    schedule 17.04.2013

Спасибо @CReaTuS, я хочу уточнить это еще немного. Обратите внимание, что в случае iOS6 мы делаем SLRequest, где в iOS5 мы должны выполнять запрос, используя TWRequest. Смотри ниже-

 ACAccountStore *accountStore = [[ACAccountStore alloc] init];
 ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

 if ( [accountStore respondsToSelector:@selector(requestAccessToAccountsWithType: options: completion:)] )
 {
 [accountStore requestAccessToAccountsWithType:accountType options:nil
 completion:^(BOOL granted, NSError *error)
 {
 dispatch_async(dispatch_get_main_queue(), ^{

 if (granted)
 {
     // Get the list of Twitter accounts.
     NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];

     // For the sake of brevity, we'll assume there is only one Twitter account present.
     // You would ideally ask the user which account they want to tweet from, if there is more than one Twitter account present.
     if ([accountsArray count] > 0) {
         // Grab the initial Twitter account to tweet from.
         ACAccount *twitterAccount = [accountsArray objectAtIndex:0];

         NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
         [tempDict setValue:@"Twitter_Name" forKey:@"screen_name"];
         [tempDict setValue:@"true" forKey:@"follow"];

        //Code specific to iOS6 or later

         SLRequest *followRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:@"https://api.twitter.com/1.1/friendships/create.json"] parameters:tempDict];

         // To unfollow hit URL-https://api.twitter.com/1.1/friendships/destroy.json

         [followRequest setAccount:twitterAccount];
         [followRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
             NSString *output = [NSString stringWithFormat:@"HTTP response status: %i", [urlResponse statusCode]];
             NSLog(@"%@", output);
             if (error) {
                 dispatch_async(dispatch_get_main_queue(), ^{
                     //Update UI to show follow request failed

                 });
             }
             else {
                 dispatch_async(dispatch_get_main_queue(), ^{
                     //Update UI to show success


                 });
             }
         }];
     }


 }
 });

 }];
 }
 else if ( [accountStore respondsToSelector:@selector(requestAccessToAccountsWithType: withCompletionHandler:)] )
 {
 [accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
 {
 dispatch_async(dispatch_get_main_queue(), ^{

 if (granted)
 {         
     // Get the list of Twitter accounts.
     NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];

     // For the sake of brevity, we'll assume there is only one Twitter account present.
     // You would ideally ask the user which account they want to tweet from, if there is more than one Twitter account present.
     if ([accountsArray count] > 0) {
         // Grab the initial Twitter account to tweet from.
         ACAccount *twitterAccount = [accountsArray objectAtIndex:0];

         NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
         [tempDict setValue:@"Twitter_Name" forKey:@"screen_name"];
         [tempDict setValue:@"true" forKey:@"follow"];

        //Code specific to iOS5

         TWRequest *followRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@"https://api.twitter.com/1/friendships/create.json"]
                                                      parameters:tempDict
                                                   requestMethod:TWRequestMethodPOST];


         [followRequest setAccount:twitterAccount];
         [followRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
             NSString *output = [NSString stringWithFormat:@"HTTP response status: %i", [urlResponse statusCode]];
             NSLog(@"%@", output);
             if (error) {
                 dispatch_async(dispatch_get_main_queue(), ^{
                     //Update UI to show follow request failed

                 });
             }
             else {
                 dispatch_async(dispatch_get_main_queue(), ^{
                     //Update UI to show success
                 });
             }
         }];
     }


 }
 });

 }];
 }
 else
 {
     dispatch_async(dispatch_get_main_queue(), ^{
         //Update UI to show follow request completely failed

     });
 }

Удачного кодирования :)

person Mohd Asim    schedule 03.02.2014
comment
SLRequest *followRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:@api.twitter.com/1.1/friendships/create.json] параметры:tempDict]; этот метод также доступен для ios 6.0 или более поздней версии, предложите альтернативный метод - person ViruMax; 18.02.2014
comment
@ViruMax внимательно посмотрите в следующем сегменте, запрос (специфический для iOS5) --> TWRequest *followRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@api.twitter.com/1/friendships/create.json] параметры:tempDict requestMethod:TWRequestMethodPOST]; - person Mohd Asim; 20.02.2014