2013-02-10 2 views
1

В настоящее время я разрабатываю приложение iOS, которое захватывает некоторые твиты из потокового api. По этой причине я беру имя пользователя и пароль пользователя для аутентификации. В дополнение к этому я хочу дать пользователю возможность следить за некоторыми людьми в твиттере. Я создал UIButton и теперь хочу вызвать URL-адрес или что-то вроде этого, чтобы следовать за конкретным пользователем. Это возможно?Twitter - Follow Button

+0

см https: //github.com/chrismaddern/Follow-Me-On-Twitter-iOS-Button –

+0

или см. http : //stackoverflow.com/questions/10379201/how-to-add-twitter-follow-button-in-my-iphone-app –

ответ

2

Если вы используете IOS 6 следовать пользователю на твиттере:

-(void)followMe 
{ 
ACAccountStore *accountStore = [[ACAccountStore alloc] init]; 
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; 

[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) { 
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"]; 
     NSLog(@"*******tempDict %@*******",tempDict); 

     //requestForServiceType 

     SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:@"https://api.twitter.com/1.1/friendships/create.json"] parameters:tempDict]; 
     [postRequest setAccount:twitterAccount]; 
     [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { 
      NSString *output = [NSString stringWithFormat:@"HTTP response status: %i Error %d", [urlResponse statusCode],error.code]; 
      NSLog(@"%@error %@", output,error.description); 
     }]; 
    } 

    } 
}]; 
} 
+0

Очень хороший ответ, именно то, что я искал ... спасибо! – RainCast

2

Просто сделать на пост

https://api.twitter.com/1.1/friendships/create.json 

POST Data: user_id=1401881&follow=true 

Reference

2
-(void)twitterButton 
{ 
NSString *twitterAccount= @"yourAccountName"; 
NSArray *urls = [NSArray arrayWithObjects: 
       @"twitter://user?screen_name={handle}", // Twitter 
       @"tweetbot:///user_profile/{handle}", // TweetBot 
       @"echofon:///user_timeline?{handle}", // Echofon 
       @"twit:///user?screen_name={handle}", // Twittelator Pro 
       @"x-seesmic://twitter_profile?twitter_screen_name={handle}", // Seesmic 
       @"x-birdfeed://user?screen_name={handle}", // Birdfeed 
       @"tweetings:///user?screen_name={handle}", // Tweetings 
       @"simplytweet:?link=http://twitter.com/{handle}", // SimplyTweet 
       @"icebird://user?screen_name={handle}", // IceBird 
       @"fluttr://user/{handle}", // Fluttr 
       @"http://twitter.com/{handle}", 
       nil]; 

UIApplication *application = [UIApplication sharedApplication]; 

for (NSString *candidate in urls) { 
    NSURL *url = [NSURL URLWithString:[candidate stringByReplacingOccurrencesOfString:@"{handle}" withString:twitterAccount]]; 
    if ([application canOpenURL:url]) 
    { 
    UIWebView* Twitterweb =[[UIWebView alloc] initWithFrame:CGRectMake(.....)]; 
     Twitterweb.delegate=nil; 
     Twitterweb.hidden=NO; 
     NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; 
     [Twitterweb loadRequest:requestObj]; 
     [self.view addSubview:Twitterweb]; 
     return; 
    } 
} 

} 
+0

Спасибо, но не совсем то, что я искал. Я сделал это, просто разместив данные на вышеуказанной странице. Но все равно спасибо! –

+0

Добро пожаловать, рад помочь – Mutawe

0

я последовал за ответ @Mohd Асим «s для реализации следующего кода Swift, спасибо за ответ. : D

Версия: IOS 10, Swift 3

Twitter API: 1,1

(https://dev.twitter.com/rest/reference/post/friendships/create)

class SocialHelper { 

static func FollowAppTwitter() { 

    let accountStore = ACAccountStore() 
    let twitterType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter) 

    accountStore.requestAccessToAccounts(with: twitterType, options: nil, 
     completion: { (isGranted, error) in 
      guard let userAccounts = accountStore.accounts(with: twitterType), 
       userAccounts.count > 0 else { return } 
      guard let firstActiveTwitterAccount = userAccounts[0] as? ACAccount else { return } 

      // post params 
      var params = [AnyHashable: Any]() //NSMutableDictionary() 
      params["screen_name"] = "pixelandme" 
      params["follow"] = "true" 

      // post request 
      guard let request = SLRequest(forServiceType: SLServiceTypeTwitter, 
            requestMethod: SLRequestMethod.POST, 
            url: URL(string: "https://api.twitter.com/1.1/friendships/create.json"), 
            parameters: params) else { return } 
      request.account = firstActiveTwitterAccount 

      // execute request 
      request.perform(handler: { (data, response, error) in 
       print(response?.statusCode) 
       print(error?.localizedDescription) 
      }) 
    }) 
} 
} 

Приглашаем Вас;)

+0

Фантастический! Эта быстрая версия - именно то, что я искал. У вас будет такая же вещь для Facebook? Я искал все, и есть много информации об интеграции, обмене и публикации FB и т. Д. Но все, что мне нужно - это «следовать за нами». Я могу получить доступ к учетной записи, но я не знаю, что добавить в SLRequest для url и params. Вы можете помочь? Thx – Mikey

+0

Привет, Мики, извините, у меня был только код Twitter. Попробуйте Google немного, я уверен, что вы можете что-то найти. Удачи! – RainCast

 Смежные вопросы

  • Нет связанных вопросов^_^