2013-09-12 2 views
1

1) Я нашел код образца пик Twitter с этой ссылкой Twitter with OAuth для интеграции.лучший способ реализовать твиттер

Я добавил ключ потребителя и секретный ключ. Но он никогда не разрешает приложение.

2) И если я использую общий комплект, он дает ошибку, что возникла проблема с запросом доступа из твиттера.
3) Если я использую социальную структуру, он будет предупреждать, если пользователь не добавил свою учетную запись в настройках.

Мне нужно, чтобы пользователь не выходил за пределы приложения для входа в Twitter.

Есть ли у кого-нибудь идеи, что было бы лучшим способом интегрироваться с твиттером?

Пожалуйста, помогите.

ответ

3

I Hope Это поможет вам. , ,

1.Add следующие классы для вашего проекта GTMOAuthAuthentication.h/м GTMOAuthSignIn.h/м GTMHTTPFetcher.h/м GTMOAuthViewControllerTouch.h/м GTMOAuthViewTouch.xib

2. Добавьте следующие рамки: Security.framework и SystemConfiguration.framework.

3 .set -ObjC вариант сборки для целевых «других флагов метки приложения».

4. Тогда пришло время для некоторого кодирования.

импорт GTMOAuthAuthentication.h и GTMOAuthViewControllerTouch.h

- (void)signInWithTwitter 
{ 
NSURL *requestURL = [NSURL URLWithString:@"https://api.twitter.com/oauth/request_token"]; 
NSURL *accessURL = [NSURL URLWithString:@"https://api.twitter.com/oauth/access_token"]; 
NSURL *authorizeURL = [NSURL URLWithString:@"https://api.twitter.com/oauth/authorize"]; 
NSString *scope = @"http://api.twitter.com/"; 

GTMOAuthAuthentication *auth = [self authForTwitter]; 

[auth setCallback:@"http://www.noop.com/OAuthCallback"]; 

GTMOAuthViewControllerTouch *viewController; 

viewController = [[GTMOAuthViewControllerTouch alloc] initWithScope:scope 
                  language:nil 
                 requestTokenURL:requestURL 
                authorizeTokenURL:authorizeURL 
                 accessTokenURL:accessURL 
                 authentication:auth 
                 appServiceName:@"AppName : Twitter" 
                  delegate:self 
finishedSelector:@selector(viewController:finishedWithAuth:error:)]; 

[appDelegate.navigationController pushViewController:viewController animated:YES]; 
} 

- (GTMOAuthAuthentication *)authForTwitter { 
GTMOAuthAuthentication *auth = [[GTMOAuthAuthentication alloc] initWithSignatureMethod:kGTMOAuthSignatureMethodHMAC_SHA1 
      consumerKey:TWITTER_CONSUMER_KEY 
      privateKey:TWITTER_CONSUMER_SECRET]; 

[auth setServiceProvider:@"Twitter"]; 

return auth; 
} 

- (void)viewController:(GTMOAuthViewControllerTouch *)viewController finishedWithAuth:(GTMOAuthAuthentication *)auth error:(NSError *)error { 

    if(error) 
    { 
     //handle error 
    } 
    else 
    { 
     // do stuff as per your app. 
    } 
} 

Примечание: если вы получаете сообщение об ошибке, как «не удалось проверить OAuth подпись и маркер», а затем проверить вас системное время правильно или нет.

+0

Я успешно зарегистрировался с помощью аутентификации twitter. На самом деле большое спасибо. Но какой будет метод для публикации изображения и ссылки на твиттер. –

1

Если вы хотите, чтобы пользователь не должен выходить за пределы вы можете использовать ACAccountStoreAccount.Framework и Social.framework для IOS 6,

NSUrl *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/users/show.json"]; 
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:twittername,@"screen_name",nil]; 

    account = [[ACAccountStore alloc] init]; 
    ACAccountType *twitterAccountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; 
    NSArray *twitterAccounts = [account accountsWithAccountType:twitterAccountType]; 

    // Runing on iOS 6 
    if (NSClassFromString(@"SLComposeViewController") && [SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) 
    { 
     [account requestAccessToAccountsWithType:twitterAccountType options:NULL completion:^(BOOL granted, NSError *error) 
     { 
      if (granted) 
      { 

       SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:url          parameters:params]; 

       [request setAccount:[twitterAccounts lastObject]]; 

       dispatch_async(dispatch_get_main_queue(),^
           { 

            [NSURLConnection sendAsynchronousRequest:request.preparedURLRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response1, NSData *data, NSError *error) 
            { 
             dispatch_async(dispatch_get_main_queue(),^
                 { 
                  if (data) 
                  { 
//                [self loadData:data]; 

                   NSString* newStr = [[NSString alloc] initWithData:data 
                              encoding:NSUTF8StringEncoding]; 
                   NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ; 


                   NSLog(@"data:%@",newStr); 
                  } 
                 }); 
            }]; 
           }); 
      } 
     }]; 
    } 
    else if (NSClassFromString(@"TWTweetComposeViewController") && [TWTweetComposeViewController canSendTweet]) // Runing on iOS 5 
    { 
     [account requestAccessToAccountsWithType:twitterAccountType withCompletionHandler:^(BOOL granted, NSError *error) 
     { 
      if (granted) 
      { 
       TWRequest *request = [[TWRequest alloc] initWithURL:url parameters:params requestMethod:TWRequestMethodGET]; 
       [request setAccount:[twitterAccounts lastObject]]; 

       dispatch_async(dispatch_get_main_queue(),^
           { 
            [NSURLConnection sendAsynchronousRequest:request.signedURLRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response1, NSData *data, NSError *error) 
            { 
             dispatch_async(dispatch_get_main_queue(),^
                 {        
                  if (data)         
                  {         
                   NSString* newStr = [[NSString alloc] initWithData:data 
                             encoding:NSUTF8StringEncoding]; 


                   NSLog(@"data:%@",newStr);               } 
                 }); 
            }]; 


           }); 
      } 
     }]; 
    } 
} 

Вы должны сохранить ACAccountStore: в .h

@property (nonatomic, strong) ACAccountStore *account; 
Смежные вопросы