我正在尝试做的事情:我有一个 url 请求(发布),我将一些信息发送到 api 服务器,然后它开始以字节为单位向我传输数据。
1)我如何在尝试设置流时发布数据,因为现在我只是使用一个 url,我可以合并NSURLRequest
一些如何?
2)为什么我的流甚至没有打开(streamStatus 返回 0),因此- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
从未被调用?,这是我最好的尝试,并且在很大程度上遵循本指南
- (void)setUpStreamFromURL:(NSURL *)path {
// iStream is NSInputStream instance variable
iStream = [[NSInputStream alloc] initWithURL:path];
[iStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[iStream open];
NSLog(@"Stream Open: %lu",[iStream streamStatus]); //return 0
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
NSLog(@"Streaming");
switch(eventCode) {
case NSStreamEventHasBytesAvailable:
{
if(!_data) {
_data = [[NSMutableData data] init];
}
uint8_t buf[1024];
unsigned int len = 0;
len = [(NSInputStream *)stream read:buf maxLength:1024];
if(len) {
[_data appendBytes:(const void *)buf length:len];
NSLog(@"DATA BEING SENT : %@", _data);
// bytesRead is an instance variable of type NSNumber.
// [bytesRead setIntValue:[bytesRead intValue]+len]; //getting error that setInt value is not part of NSNumber, and thats true so not sure what to do about it, but this isn't the issue.
} else {
NSLog(@"no buffer!");
}
break;
}
case NSStreamEventEndEncountered:
{
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
stream = nil; // stream is ivar, so reinit it
break;
}
// continued ...
}
}
如果它有帮助,我的头文件:
#import <Foundation/Foundation.h>
#import "Login.h"
@interface Stream : NSStream <NSStreamDelegate> {
NSMutableArray *searchIdList;
NSInputStream *iStream;
NSNumber *bytesRead;
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode ;
-(id)initWithLoginObject:(Login *)log;
@property NSMutableData *data;
@end