Twitter的流API - Objective-C的
问题描述:
我与工作Twitter的REST /流式API。当我想访问REST API时,我创建了一个NSMutableURLRequest
(包含访问令牌和查询等参数)。然后,我使用请求与NSURLSession
一起加载数据。我使用它为我创建的可变请求对象库(如果我不使用请求对象,那么Twitter的API不会允许我访问相关的用户数据)。Twitter的流API - Objective-C的
现在我想通过流API加载Twitter的时间表。我遇到的一个问题是,我无法弄清楚如何使用我的自定义可变请求对象和NSStream
对象。我唯一能做的就是设置host
URL链接。但是,这还不够好,因为我需要通过用户的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];
答
我设法解决我的问题。我试图从CFStream
很多的解决方案,网络插座库....才发现,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。