iosafnetworking-3

How to set outputStream in AFNetworking 3.0


I had an option in older AFNetworking to set outputStream with:

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

How can I achieve this in AFNetworking 3.0?


Solution

  • Set the setDataTaskDidReceiveDataBlock on the AFHTTPSessionManager to write the data to a buffer. Then write that buffer to a file using the 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:...]
    

    Then refer to this Apple guide to use an NSOutputStream and the stream delegate callback method below to write the data to a file: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Streams/Articles/WritingOutputStreams.html

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