【问题标题】:Twitter Streaming API - Objective-CTwitter 流 API - Objective-C
【发布时间】:2018-01-07 00:56:45
【问题描述】:

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

现在我正在尝试通过流 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];

【问题讨论】:

    标签: objective-c twitter streaming nsstream cfreadstream


    【解决方案1】:

    更新

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

    我的解决方案

    我设法解决了我的问题。我尝试了从CFStream 到 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。

    【讨论】:

      猜你喜欢
      • 2012-06-12
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      相关资源
      最近更新 更多