2012-02-24 9 views
5

Zasadniczo to, czego chcę, to aplikacja, gdy użytkownik zezwoli na dostęp do swojego konta na Twitterze, aby móc dodawać tweety niezależnie od tego, który użytkownik wybrał w a UITableView. Idealnie chciałbym użyć platformy Twitter na iOS 5, ale głównym problemem, jaki mam, jest kontroler widoku modalnego do tweetowania. Czy to opcjonalne? Czy możliwe jest tweetowanie bez niego, a jeśli nie, to co sugerujesz?iOS 5 Twitter Framework: Tweeting bez wprowadzania i potwierdzania przez użytkownika (modalny kontroler widoku)

Dzięki!

Odpowiedz

11

Z pewnością możliwe jest tweetowanie bez niego, w aplikacji iOS 5 są dostępne następujące aplikacje. Nawet jeśli użytkownik nie zarejestrował konta, przenosi użytkownika nawet do wymaganej sekcji preferencji.

- (void)postToTwitter 
{ 
    // Create an account store object. 
    ACAccountStore *accountStore = [[ACAccountStore alloc] init]; 

    // Create an account type that ensures Twitter accounts are retrieved. 
    ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; 

    // Request access from the user to use their Twitter accounts. 
    [accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) { 
     if(granted) { 
      // Get the list of Twitter accounts. 
      NSArray *accountsArray = [accountStore accountsWithAccountType:accountType]; 


      if ([accountsArray count] > 0) { 
       // Grab the initial Twitter account to tweet from. 
       ACAccount *twitterAccount = [accountsArray objectAtIndex:0]; 
       TWRequest *postRequest = nil; 

       postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@"http://api.twitter.com/1/statuses/update.json"] parameters:[NSDictionary dictionaryWithObject:[self stringToPost] forKey:@"status"] requestMethod:TWRequestMethodPOST]; 



       // Set the account used to post the tweet. 
       [postRequest setAccount:twitterAccount]; 

       dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) { 
        [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { 
         dispatch_async(dispatch_get_main_queue(), ^(void) { 
          if ([urlResponse statusCode] == 200) { 
           Alert(0, nil, @"Tweet Successful", @"Ok", nil); 
          }else { 

           Alert(0, nil, @"Tweet failed", @"Ok", nil); 
          } 
         }); 
        }]; 
       }); 

      } 
      else 
      { 
       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=TWITTER"]]; 
      } 
     } 
    }]; 
} 
+0

dzięki wielkie kolego. – sooper

+0

@Sooper Nie ma problemu –

+0

co z dodawaniem obrazu? –

6

Byłoby zaktualizowaną wersję używając SLRequest zamiast TWRequest, która została zaniechana w iOS 6. Uwaga ta potrzebuje społecznego i kont ramy mają być dodane do projektu ...

- (void) postToTwitterInBackground { 

    // Create an account store object. 
    ACAccountStore *accountStore = [[ACAccountStore alloc] init]; 

    // Create an account type that ensures Twitter accounts are retrieved. 
    ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; 

    // Request access from the user to use their Twitter accounts. 
    [accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) { 
     if(granted) { 
      // Get the list of Twitter accounts. 
      NSArray *accountsArray = [accountStore accountsWithAccountType:accountType]; 

      if ([accountsArray count] > 0) { 
       // Grab the initial Twitter account to tweet from. 
       ACAccount *twitterAccount = [accountsArray objectAtIndex:0]; 
       SLRequest *postRequest = nil; 

       // Post Text 
       NSDictionary *message = @{@"status": @"Tweeting from my iOS app!"}; 

       // URL 
       NSURL *requestURL = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/update.json"]; 

       // Request 
       postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:requestURL parameters:message]; 

       // Set Account 
       postRequest.account = twitterAccount; 

       // Post 
       [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { 
        NSLog(@"Twitter HTTP response: %i", [urlResponse statusCode]); 
       }]; 

      } 
     } 
    }]; 

} 
+0

działa jak urok! Od jakiegoś czasu szukałem tej aktualizacji. dzięki –

+0

moja przyjemność .... –

+0

Próbuję tego, ale otrzymuję błąd 403 od Twittera .. jakieś pomysły? – RyanG

5

Aktualizacja: TwitterKit in Fabric by Twitter jest bardzo przydatny i jeśli chcesz publikować w aplikacji Twitter, gdy użytkownik próbuje Tweetować w swojej aplikacji, może być dobrym rozwiązaniem.

(TAK, ta metoda umożliwia publikowanie w serwisie Twitter bez okna dialogowego lub potwierdzenia).

TwitterKit zajmie się częścią uprawnień i za pomocą TWTRAPIClient wykonujemy tweet za pośrednictwem interfejsów API dla reszty Twittera.

//Needs to performed once in order to get permissions from the user to post via your twitter app. 
[[Twitter sharedInstance]logInWithCompletion:^(TWTRSession *session, NSError *error) { 
    //Session details can be obtained here 
    //Get an instance of the TWTRAPIClient from the Twitter shared instance. (This is created using the credentials which was used to initialize twitter, the first time) 
    TWTRAPIClient *client = [[Twitter sharedInstance]APIClient]; 

    //Build the request that you want to launch using the API and the text to be tweeted. 
    NSURLRequest *tweetRequest = [client URLRequestWithMethod:@"POST" URL:@"https://api.twitter.com/1.1/statuses/update.json" parameters:[NSDictionary dictionaryWithObjectsAndKeys:@"TEXT TO BE TWEETED", @"status", nil] error:&error]; 

    //Perform this whenever you need to perform the tweet (REST API call) 
    [client sendTwitterRequest:tweetRequest completion:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 
    //Check for the response and update UI according if necessary.    
    }]; 
}]; 

Mam nadzieję, że to pomoże.

+0

Dziękujemy! To działało idealnie i twój przykład był naprawdę jedynym, jaki mogłem znaleźć. Chciałbym, żeby twitter miał to w swoich dokumentach. – dirkoneill

+0

Cieszę się, że pomogło Ci to @dirkoneill. BTW initWithConsumerKey nie działa już z wersją TwitterKit v1.4.0, która została wydana kilka dni temu. Odpowiednio zaktualizowałem odpowiedź. –

+0

Tego właśnie szukałem przez jeden dzień. To zadziałało dla mnie. Wzniesione !!! – NSPratik

1

Przyjęta odpowiedź nie jest już ważna z powodu kilku zmian. Ten działa z iOS 10, Swift 3 oraz wersją 1.1 interfejsu API serwisu Twitter.

** UPDATE **

Ta odpowiedź została zaktualizowana jak poprzedni polegać na nieaktualnych Twitter końcowego.

import Social 
import Accounts 

func postToTwitter() { 
    let accountStore = ACAccountStore() 
    let accountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter) 

    accountStore.requestAccessToAccounts(with: accountType, options: nil) { (granted, error) in 
     if granted, let accounts = accountStore.accounts(with: accountType) { 
      // This will default to the first account if they have more than one 

      if let account = accounts.first as? ACAccount { 
       let requestURL = URL(string: "https://api.twitter.com/1.1/statuses/update.json") 
       let parameters = ["status" : "Tweet tweet"] 
       guard let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .POST, url: requestURL, parameters: parameters) else { return } 
       request.account = account 
       request.perform(handler: { (data, response, error) in 
        // Check to see if tweet was successful 
       }) 
      } else { 
       // User does not have an available Twitter account 
      } 
     } 
    } 
} 

This is the API który jest używany.

+0

Czy to nadal działa? Miał pewne problemy z Swift. Otrzymuję również błąd 403. – Jonny

+0

@Jonny Ja zaktualizowałem odpowiedź, właśnie przetestowałem teraz, by potwierdzić to działa. – CodeBender

+0

Wielkie dzięki! W międzyczasie udało mi się go uruchomić, korzystając z pakietu SDK TwitterKit zainstalowanego przez Fabric. Przepływ jest bardzo podobny ... Chyba różnica polega na tym, że ACAccountStore wykorzystuje istniejącą aplikację iOS na Twitterze, a TwitterKit używa aplikacji, którą musimy zarejestrować na stronie apps.twitter.com ... – Jonny

Powiązane problemy