我想用相应的 URL 从服务器读取流数据,目前我正在尝试使用 NSInputStream 读取数据,但我收到错误“错误 2 操作无法完成。没有这样的文件或目录”。Web 开发人员以字节形式接收数据,然后他将该数据转换为 Stream,如 MemoryStream(byteData)[注意:Web 服务是用 .net 编写的],并返回给我。读取这种数据的方法是什么,我尝试了 AISHTTPRequest 得到了大小为 0 字节的文件,我再次尝试了 NSURLConnction 我得到了大小为 0 字节的文件,现在我正在使用 NSInputStream 我得到了提到的错误在开始。这是我的 NSInputStream 代码,
请指导我是否可以读取这种数据是iOS作为前端,如果是,那么指导我应该如何与这种数据进行交互。如果 NSInputStream 是与之交互的预期方式,那么下面编写的代码中的问题是什么。
- (void)setUpStreamForFile {
NSString *urlStr = @"http://192.168.1.201/example/example.svc/example?parameter={\"DCU_DocId\":\"05e24018-b728-4ec8-9848-d6cae02bec95\"}";
// iStream is NSInputStream instance variable
iStream = [[NSInputStream alloc] initWithFileAtPath:urlStr];
[iStream setProperty:[NSDictionary dictionaryWithObjectsAndKeys:(id) kCFBooleanFalse, kCFStreamSSLValidatesCertificateChain, nil ] forKey:(NSString *) kCFStreamPropertySSLSettings];
[iStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[iStream open];
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
_data = [[NSMutableData alloc] init];
int bytesRead=0;
switch(eventCode) {
case NSStreamEventHasBytesAvailable:
{
if(!_data) {
}
uint8_t buf[20480];
unsigned int len = 0;
len = [(NSInputStream *)stream read:buf maxLength:20480];
if(len) {
[_data appendBytes:(const void *)buf length:len];
// bytesRead is an instance variable of type NSNumber.
//[bytesRead setIntValue:[bytesRead intValue]+len];
bytesRead = bytesRead +len;
NSLog(@"bytesRead:%d",bytesRead);
}
else {
NSLog(@"no buffer!");
}
break;
}
case NSStreamEventEndEncountered:
{
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
stream = nil; // stream is ivar, so reinit it
break;
}
case NSStreamEventErrorOccurred:
{
NSError *theError = [stream streamError];
UIAlertView *theAlert = [[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"Error %i: %@",[theError code], [theError localizedDescription]] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
NSLog(@"Error %i %@",[theError code], [theError localizedDescription]);
[theAlert show];
[stream close];
break;
}
case NSStreamEventOpenCompleted:
{
NSLog(@"EventOpen");
}
case NSStreamEventHasSpaceAvailable:
{
NSLog(@"EventHasSpac");
}
case NSStreamEventNone:
{
NSLog(@"EventNone");
}
}
}