2009-04-30 65 views
3

我想寫一個NSOutputStream到服務器與蘋果的示例代碼:真的iPhone設備上有沒有像'getStreamsToHost'的東西?


NSURL *website = [NSURL URLWithString:str_IP]; 
NSHost *host = [NSHost hostWithName:[website host]]; 
[NSStream getStreamsToHost:host port:1100 inputStream:nil outputStream:&oStream]; 
[oStream retain]; 
[oStream setDelegate:self]; 
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
[oStream open]; 

這些代碼行之有效的iPhone模擬器,但是當我把它建到真實的設備。兩個警告彈出。問題是:

1)類NSHost不屬於iPhone OS的庫

2)getStreamsToHost沒有發現任一

的替代方法或類的任何建議它可以在實際設備中使用?

回答

12

由於CFWriteStream是toll-free bridged到NSOutputStream可以使用CFStreamCreatePairWithSocketToHost讓你流對:

CFReadStreamRef readStream = NULL; 
CFWriteStreamRef writeStream = NULL; 
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (CFStringRef)host, port, &readStream, &writeStream); 
if (readStream && writeStream) { 
    CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue); 
    CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue); 

    inputStream = (NSInputStream *)readStream; 
    [inputStream retain]; 
    [inputStream setDelegate:self]; 
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
    [inputStream open]; 

    outputStream = (NSOutputStream *)writeStream; 
    [outputStream retain]; 
    [outputStream setDelegate:self]; 
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; 
    [outputStream open]; 
} 

if (readStream) 
    CFRelease(readStream); 

if (writeStream) 
    CFRelease(writeStream); 
+0

感謝。還有一個問題:'kCFStreamPropertyShouldCloseNativeSocket'也找不到。我應該使用'kCFStreamPropertySocketNativeHandle'而不是爲CFWriteStream設置屬性? – 2009-05-02 10:57:47

+1

它在那裏,你可能需要#include 2009-05-02 23:49:58

+0

這是[執行的類別](https://developer.apple.com/library/ios/qa/qa1652/_index.html)由蘋果。 – DanSkeel 2014-08-26 05:45:37