Twitter 流媒体 API - Objective-C

Twitter Streaming API - Objective-C

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

现在我正尝试通过流媒体加载 Twitter 时间线 API。我遇到的一个问题是我不知道如何使用带有 NSStream 对象的自定义可变请求对象。我唯一能做的就是设置 host URL link。但这还不够好,因为我需要传递用户 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];

UPDATE

Due to changes in the Twitter API, the streaming API will no longer be available. I'll keep my answer here just in case anyone is still working with the streaming API, but the API won't be up for much longer. Instead you'll have to manually refresh the data you want every few seconds/minutes - how often you refresh the data is down to your user-base, the larger the user-base the longer the refresh intervals should be.

我的解决方案

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

我最终使用 NSURLSession 及其关联的委托方法来设置和加载来自 Twitter API 的连续数据流。完美运行并且设置起来非常简单:

在您的 header 中设置委托:<NSURLSessionDelegate>

下面代码中的

request 是我创建的 NSURLRequest object,它存储 Twitter 流 URL、查询参数和用户 OAuth身份验证 header 数据。

创建 URL request/session objects:

// 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。