如何在iOS中改进我的TWTweetComposeViewController代码?

我已经实现了以下代码来进行Twitter共享。 在我的代码中,我尝试测试iOS 5,如果这不起作用,我将回到使用ShareKit的Twitter代码进行共享的旧方式。

我向同事展示了代码,他建议我的代码可能有缺陷,我需要做两件事:

  1. 做一个适当的运行时间检查?? (因为它可能会在IOS 4及更早版本上崩溃)即使它没有。
  2. 弱链接Twitter框架工作

有人可以解释一下正确的运行时检查是什么吗? 为什么弱链接?

NSString *text = [NSString stringWithFormat:@"@Awesome chart: %@", self.titleLabel.text]; 

 if ([TWTweetComposeViewController canSendTweet]) { TWTweetComposeViewController *tweetComposeViewController = [[TWTweetComposeViewController alloc] init]; [tweetComposeViewController setInitialText:text]; [tweetComposeViewController addImage:image]; [tweetComposeViewController setCompletionHandler:^(TWTweetComposeViewControllerResult result){ dispatch_async(dispatch_get_main_queue(), ^{ [self dismissModalViewControllerAnimated:YES]; if (result == TWTweetComposeViewControllerResultDone) { NSLog(@"iOS 5 onwards Twitter share complete"); } }); }]; [self presentViewController:tweetComposeViewController animated:YES completion:^{ }]; } else { SHKItem *item = [SHKItem image:image title:text]; // Share the message. [SHKTwitter shareItem:item]; NSLog(@"Device does not support Twitter library"); } } 

弱链接仅意味着框架不需要在设备上。 或者换句话说,当您将框架添加到项目中时,应用程序将要求该框架位于设备上。 因此,如果你需要一个框架,而不是,那么应用程序将崩溃。 在您的情况下,如果您希望应用程序在iOS 5之前的iOS版本(即iOS 4.x)上运行,您可能希望弱化链接twitter框架。

正确的运行时检查意味着您应该将应用程序加载到您的设备上(运行iOS 5或更高版本)并测试应用程序的推特function。 如果它崩溃了,那么你知道你有问题。

我浏览了你的代码,一切看起来都很好。 我没有通过我的编译器运行它,所以我不能说语法错误等。 我要做的一个改变是:

if ([TWTweetComposeViewController canSendTweet])

  Class twClass = NSClassFromString(@"TWTweetComposeViewController"); if (!twClass) // Framework not available, older iOS return; 

我使用它的原因是因为字面上检查框架是否在该设备上,而canSendTweet检查用户是否已登录。所以我不想混淆未登录的用户与设备没有登录的用户用iOS 5支持Twitter。

如果您需要帮助,请告诉我。

DETweetComposeViewController是另一种选择。 它也与iOS 4兼容。

我认为你也泄漏了控制器(就像我见过的大多数代码样本一样)。

另一方面,您注意了有关完成处理程序的文档,并正确地确保您在主线程中执行UI工作。 我需要修复我的实现来做同样的事情。