【问题标题】:Simple GET request with Twitter API in iOSiOS 中使用 Twitter API 的简单 GET 请求
【发布时间】:2017-01-24 02:44:33
【问题描述】:

有谁知道如何在 iOS 中使用 Twitter API 对用户的时间线进行简单的 GET 请求?
https://dev.twitter.com/rest/reference/get/statuses/user_timeline

我意识到那里有多个框架,但这就是我所需要的,并且不希望仅仅为此使用它们。我也不想在 iOS 上使用 Social 框架,因为它要求用户拥有 Twitter 帐户。

我已经从这里的这篇文章中用 PHP 实现了这个,但不确定如何在 iOS 中做同样的事情。 https://stackoverflow.com/a/12939923/284714

【问题讨论】:

  • 你没有提到任何关于 Fabric 的事情。所以我想知道你是否尝试过在 Twitter 上使用 Fabric for iOS 或 docs.fabric.io/apple/fabric/overview.html ? Fabric 可以帮助您将 Twitter SDK 安装到您的项目中,然后您可以使用此示例从 Twitter docs.fabric.io/apple/twitter/… 执行 GET 请求
  • 是的,我知道 Fabric,但我不想使用它。
  • 好的,没问题。顺便说一句,如果你在这里创建一个 Twitter 应用程序 apps.twitter.com 并获取访问/密钥。您可以使用它们来消除上面提到的要求用户拥有 Twitter 帐户的限制

标签: ios objective-c twitter twitter-rest-api


【解决方案1】:

以下是使用 NSURLSession 的方法,这是在 iOS/macOS 上当前的、现代的、“面向未来的”(lol) 方式:

NSURLSession *urlSession;
NSURLSessionDataTask *dataTask;
NSURL *twitterURL = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/user_timeline.json"];

urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
dataTask = [urlSession
            dataTaskWithURL:twitterURL
            completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

                // add error checking here
                NSLog(@"Got %lu bytes of data from twitter", (unsigned long)[data length]);

            }];
[dataTask resume];

如果 swift 是你的一杯茶:

let defaultSession = URLSession(configuration: URLSessionConfiguration.default)
var dataTask: URLSessionDataTask?
let url: URL! = URL(string: "https://api.twitter.com/1.1/statuses/user_timeline.json");
dataTask = defaultSession.dataTask(with: url) {
    (data, response, error) in
    // check errors and stuff.
    print(data)
}
dataTask?.resume()

【讨论】:

  • 谢谢你。如果您也可以包含 swift 版本,那就太棒了
  • @Suhaib 天哪,我知道有人会问这个 :) 我添加了一个 swift 版本。
  • 这不是一个简单的请求就能完成的事情。他们必须使用 OAuth 进行授权。这是我不知道如何在iOS中实现的部分。
  • 此代码给出了错误的身份验证数据错误
【解决方案2】:

在 iOS 上执行此操作的一种快速方法是使用 ACAccountStore 类来获取用户经过身份验证的 Twitter 帐户之一,然后使用 SLRequest 执行请求。 SLRequest 有一个 account 属性,您可以使用它来包含该帐户。

【讨论】:

  • 感谢您的回答。是的,我知道该课程,但我不想要求用户拥有 Twitter 帐户。
  • 从 API v1.1 开始,所有 Twitter API 请求都需要帐户身份验证
  • 是的,我知道,但使用 ACAccountStore 要求用户自己使用 Twitter 帐户登录。我想从任意时间线获取推文,而不需要用户拥有 Twitter 帐户。
猜你喜欢
  • 2019-12-26
  • 1970-01-01
  • 2021-03-12
  • 2018-07-25
  • 2021-03-11
  • 2022-08-17
  • 2015-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多