iOS 5 Twitter框架:无需用户输入和确认即可发布推文(模态视图控制器)

6
基本上我想要的是,一旦用户允许访问他们的Twitter帐户,应用程序就能够在UITableView中选择的内容进行推文。理想情况下,我想使用iOS 5中的Twitter框架,但我遇到的主要问题是推文的模态视图控制器。这是可选的吗?如果不能没有它,你有什么建议?谢谢!
4个回答

11

不使用Twitter框架也可以进行推文,以下代码已在生产中用于iOS 5应用程序。如果用户没有注册帐户,则它甚至会将其带到必要的偏好设置部分。

- (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"]];
            }
        }
    }];
}

添加一张图片怎么样? - jesses.co.tt
这在iOS 6中似乎已经被弃用了? - jesses.co.tt
@jesses.co.tt 我记得以前发送带有图片的 TWRequest 没有问题。不过这篇文章已经两年了,很多东西可能已经改变了。 - james_womack
@Cirrostratus 是的,一旦我查看了文档,我发现 addMultiPartData 方法解决了问题。 - jesses.co.tt
谢谢,这真的很有帮助,省去了我大量的搜索和阅读!确保在URLWithString中使用https而不是http,否则您将收到403错误。 - isa56k

6

这将是使用SLRequest而不是在iOS 6中已经废弃的TWRequest更新版本。 请注意,需要将Social和Accounts框架添加到您的项目中...

- (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]);
                 }];

            }
        }
    }];

}

运行得很好!我已经寻找这个更新一段时间了。谢谢。 - Amit Hagin
我正在尝试这个,但是从Twitter返回了一个403错误。有什么想法吗? - RyanG
由于 Twitter 推出了新的 API,因此更新了 API 链接。 - Leena

5
更新:Twitter的Fabric中的TwitterKit非常方便,如果你想在用户尝试在你的应用程序中发布推文时从你的Twitter应用程序中发布,则考虑使用此选项可能是一个不错的选择。(是的,这种方法将允许您在无需任何对话框或确认的情况下发布到twitter)。
TwitterKit将处理权限部分,并使用TWTRAPIClient通过Twitter rest API执行推文。
 //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.            
   }];
}];

希望这可以帮到你。

谢谢!这个完美地运行了,而且你的例子真的是我能找到的唯一一个。我希望Twitter的文档中也有这个。 - YoungDinosaur
很高兴知道它能帮到你@dirkoneill。顺便说一句,initWithConsumerKey在TwitterKit v1.4.0中不再使用,这是几天前发布的。已经相应地更新了答案。 - Vijay Tholpadi
请注意,loginWithCompletionHandler 应该只被调用一次,而不是每次尝试发布推文时都调用,就像 @etayluz 的编辑所示。但第一次调用时将其放在完成块中会很有帮助。 - Vijay Tholpadi
没错 - 但是即使用户已经退出登录,调用它也不会有任何影响,因此你需要单独的逻辑来检查用户是否已经登录,即使用户已经登录,完成块仍然会被调用。 - etayluz

2

由于多次更改,原先被接受的答案已经不再有效。这个新答案适用于 iOS 10、Swift 3 和 Twitter API 的 1.1 版本。

** 更新 **

此答案已更新,因为之前的答案依赖于一个已弃用的 Twitter 端点。

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
            }
        }
    }
}

正在使用的API


这还能用吗?它在Swift方面有一些问题。同时返回403错误。 - Jonny
@Jonny 我更新了答案,刚才测试确认它可以工作。 - CodeBender
非常感谢!与此同时,我已经通过Fabric安装的TwitterKit SDK使其正常工作。流程非常相似...我想区别在于ACAccountStore使用iOS中现有的Twitter应用程序,而TwitterKit使用我们自己在apps.twitter.com上注册的应用程序... - Jonny

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接