草庐IT

ios - 在 iOS 中访问用户的 Twitter 帐户

coder 2024-01-20 原文

以下代码应该请求访问权限,然后检索用户的 Twitter 帐户,以便将帐户与 iOS 应用程序同步。下面是我要执行的操作的代码。

- (IBAction)connectToTwitter:(id)sender {
    // borrowed from: http://eflorenzano.com/blog/2012/04/18/using-twitter-ios5-integration-single-sign-on/
 ACAccountStore *store = [[ACAccountStore alloc] init];
 ACAccountType *twitterType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[store requestAccessToAccountsWithType:twitterType options:nil completion:^(BOOL granted, NSError *error) 
{
if(granted) {
// Access has been granted, now we can access the accounts
// Remember that twitterType was instantiated above
NSArray *twitterAccounts = [store accountsWithAccountType:twitterType];

// If there are no accounts, we need to pop up an alert
if(twitterAccounts != nil && [twitterAccounts count] == 0)
 {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Twitter Accounts"
                                                                message:@"There are no Twitter accounts configured. You must add or create a Twitter separately."
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
                [alert show];
} else {
ACAccount *account = [twitterAccounts objectAtIndex:0];
// Do something with their Twitter account
NSURL *url = [NSURL URLWithString:@"http://api.twitter.com/1/account/verify_credentials.json"];
                SLRequest *req = [SLRequest requestForServiceType:SLServiceTypeTwitter
                                                    requestMethod:SLRequestMethodPOST
                                                              URL:url
                                                       parameters:nil];
// Important: attach the user's Twitter ACAccount object to the request
req.account = account;
[req performRequestWithHandler:^(NSData *responseData,
                                                 NSHTTPURLResponse *urlResponse,
                                                 NSError *error) 
{
 // If there was an error making the request, display a message to the user
if(error != nil) {
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Twitter Error"
                                                                        message:@"There was an error talking to Twitter. Please try again later."
                                                                       delegate:nil
                                                              cancelButtonTitle:@"OK"
                                                              otherButtonTitles:nil];
                        [alert show];
                        return;
}
 // Parse the JSON response
 NSError *jsonError = nil;
                    id resp = [NSJSONSerialization JSONObjectWithData:responseData
                                                              options:0
                                                                error:&jsonError];
// If there was an error decoding the JSON, display a message to the user
 if(jsonError != nil)
 {
 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Twitter Error"
                                                                        message:@"Twitter is not acting properly right now. Please try again later."
                                                                       delegate:nil
                                                              cancelButtonTitle:@"OK"
                                                              otherButtonTitles:nil];
                        [alert show];
                        return;
 }

NSString *screenName = [resp objectForKey:@"screen_name"];
self.twitterHandle = screenName;
PFUser *currentUser = [PFUser currentUser];
PFQuery *query = [PFQuery queryWithClassName:@"_User"];
[query whereKey:@"username" equalTo:currentUser.username];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// Do something with the found objects
for (PFObject *object in objects)
 {
object[@"TwitterHandle"] = self.twitterHandle;
[object saveInBackground];
}
} else {
// Log details of the failure
NSLog(@"Error: %@ %@", error, [error userInfo]);
}
}];
}];
}
}
}];
}

目前,此代码在模拟器中工作,因为它检测到没有要同步的 Twitter 帐户。但是,在实际设备上,当在手机上的 Twitter 应用程序上登录 Twitter 帐户时,应用程序会在用户允许访问后崩溃。我不知道我的代码问题出在哪里。比较难,因为在模拟器上运行的很好,但是不能下载推特在模拟器上放账号。

首先,我的代码有什么问题,我该如何解决?其次,我如何在模拟器中对此进行测试,这样我就不必在每次进行简单更改并想要测试它时都将应用程序重新下载到我的设备上?

最佳答案

iOS 默认检查 iOS 设置中的 Twitter 帐户,而不是通过 Twitter 应用程序。检查那里

您可以添加一个异常断点来找出崩溃的位置。在这里查看我的答案以找到崩溃位置。 Crash that not able to get

编辑: 好吧,我只是把你的代码和测试自己。您代码中的所有内容均有效,我能够检索到此行的信息。

NSString *screenName = [resp objectForKey:@"screen_name"];
self.twitterHandle = screenName;

那是 twitter 正确返回数据,我 NSlogged 屏幕名称,我知道了。

但只有一个小的变化 verifyCredentials 服务是一个 GET 方法,只需将 SLRequest requestMethod 更改为 SLRequestMethodGET

您已经创建了一些名为 PFUser 和 PFQuery 的对象,但我无法获取,您可能应该检查一下

关于ios - 在 iOS 中访问用户的 Twitter 帐户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20852000/

有关ios - 在 iOS 中访问用户的 Twitter 帐户的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  3. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  4. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  5. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  6. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  7. ruby-on-rails - 简单的 Ruby on Rails 问题——如何将评论附加到用户和文章? - 2

    我意识到这可能是一个非常基本的问题,但我现在已经花了几天时间回过头来解决这个问题,但出于某种原因,Google就是没有帮助我。(我认为部分问题在于我是一个初学者,我不知道该问什么......)我也看过O'Reilly的RubyCookbook和RailsAPI,但我仍然停留在这个问题上.我找到了一些关于多态关系的信息,但它似乎不是我需要的(尽管如果我错了请告诉我)。我正在尝试调整MichaelHartl'stutorial创建一个包含用户、文章和评论的博客应用程序(不使用脚手架)。我希望评论既属于用户又属于文章。我的主要问题是:我不知道如何将当前文章的ID放入评论Controller。

  8. ruby - RVM "ERROR: Unable to checkout branch ."单用户 - 2

    我在新的Debian6VirtualBoxVM上安装RVM时遇到问题。我已经安装了所有需要的包并使用下载了安装脚本(curl-shttps://rvm.beginrescueend.com/install/rvm)>rvm,但以单个用户身份运行时bashrvm我收到以下错误消息:ERROR:Unabletocheckoutbranch.安装在这里停止,并且(据我所知)没有安装RVM的任何文件。如果我以root身份运行脚本(对于多用户安装),我会收到另一条消息:Successfullycheckedoutbranch''安装程序继续并指示成功,但未添加.rvm目录,甚至在修改我的.bas

  9. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  10. ruby - 有没有办法从 ruby​​ case 语句中访问表达式? - 2

    我想从then子句中访问c​​ase语句表达式,即food="cheese"casefoodwhen"dip"then"carrotsticks"when"cheese"then"#{expr}crackers"else"mayo"end在这种情况下,expr是食物的当前值(value)。在这种情况下,我知道,我可以简单地访问变量food,但是在某些情况下,该值可能无法再访问(array.shift等)。除了将expr移出到局部变量然后访问它之外,是否有直接访问caseexpr值的方法?罗亚附注我知道这个具体示例很简单,只是一个示例场景。 最佳答案

随机推荐