如何在AFNetworking 3.0中设置outputStream

时间:2016-12-05 11:44:44

标签: ios afnetworking-3

我在较旧的AFNetworking中有一个选项可以设置outputStream:

AFHTTPRequestOperation* requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
requestOperation.outputStream = [NSOutputStream outputStreamToFileAtPath:somePath append:NO];

如何在AFNetworking 3.0中实现这一目标?

1 个答案:

答案 0 :(得分:3)

在AFHTTPSessionManager上设置setDataTaskDidReceiveDataBlock以将数据写入缓冲区。然后使用NSOutputStream将该缓冲区写入文件。

NSString *baseURLString = @"https://www.whatever.com";
NSString *pathString = "lol/rofl/";

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:baseURLString]];
manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

[manager setDataTaskDidReceiveDataBlock:^(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSData * _Nonnull data) {
    [self.dataBuffer appendBytes:[data bytes] length:data.length];
}];

[manager GET:pathString parameters:nil progress:...]

然后参考本Apple指南,使用NSOutputStream和下面的流委托回调方法将数据写入文件:https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Streams/Articles/WritingOutputStreams.html

 - (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode