2017-07-31 65 views
0

我與工作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]; 

回答

1

我設法解決我的問題。我試圖從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。