0

我正在使用Twitter REST/Streaming API。当我想访问 REST API 时,我创建了一个NSMutableURLRequest(包含访问令牌和查询等参数)。然后我结合使用请求NSURLSession来加载数据。我正在使用一个为我创建可变请求对象的库(如果我不使用请求对象,那么 Twitter API 将不允许我访问相关的用户数据)。

现在我正在尝试通过流 API 加载 Twitter 时间线。我遇到的一个问题是我无法弄清楚如何将我的自定义可变请求对象与NSStream对象一起使用。我唯一能做的就是设置hostURL 链接。但这还不够好,因为我需要传递用户 OAuth 数据(包含在可变请求对象中),以便 Twitter API 允许我访问用户数据。

如何将请求对象附加到流?这是我的代码:

NSURL *website = [NSURL URLWithString:@"https://userstream.twitter.com/1.1/user.json"];

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)[website host], 80, &readStream, &writeStream);

NSInputStream *inputStream = (__bridge_transfer NSInputStream *)readStream;
NSOutputStream *outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
4

1 回答 1

1

更新

由于 Twitter API 的变化,流式传输 API 将不再可用。我将在此处保留我的答案,以防万一有人仍在使用流式 API,但该 API 不会持续太久。相反,您必须每隔几秒/分钟手动刷新一次您想要的数据 - 您刷新数据的频率取决于您的用户群,用户群越大,刷新间隔应该越长。

我的解决方案

我设法解决了我的问题。我尝试了许多从CFStreamWeb 套接字库到 Web 套接字库的解决方案......只是发现 Twitter 流 API 不支持套接字......很好的开始!

我最终使用NSURLSession及其相关的委托方法,从 Twitter API 设置和加载连续的数据流。完美运行并且非常容易设置:

在标题中设置委托:<NSURLSessionDelegate>

request下面的代码中是NSURLRequest我创建的一个对象,它存储 Twitter 流 URL、查询参数和用户OAuth身份验证标头数据。

创建 URL 请求/会话对象:

// Set the stream session.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
               
// Start the data stream.
[[session dataTaskWithRequest:request] resume];

最后设置委托方法:

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    
    NSError *feedError = nil;
    NSDictionary *feed = [NSJSONSerialization JSONObjectWithData:data options:0 error:&feedError];
    NSLog(@"%@", feed);
}

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    
    if (error) {
        NSLog(@"%@", error);
    }
}

而已!现在您所要做的就是解析feed字典中返回的数据并相应地更新您的 UI。

于 2017-08-04T09:42:17.783 回答