Wednesday, May 1, 2013

NSMutableURLRequest setHTTPBodyStream example ios


setHTTPBodyStream:

Sets the request body of the receiver to the contents of a specified input stream.
- (void)setHTTPBodyStream:(NSInputStream *)inputStream
Parameters of [NSMutableURLRequest setHTTPBodyStream]
inputStream
The input stream that will be the request body of the receiver. The entire contents of the stream will be sent as the body, as in an HTTP POST request. The inputStream should be unopened and the receiver will take over as the stream’s delegate.
Discussion of [NSMutableURLRequest setHTTPBodyStream]
Setting a body stream clears any data set by setHTTPBody:. These values are mutually exclusive.
Example of [NSMutableURLRequest setHTTPBodyStream]
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uploadURL];
NSInputStream *stream = [[NSInputStream alloc] initWithFileAtPath:filePath];
[request setHTTPBodyStream:stream];
[request setHTTPMethod:@"POST"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    NSLog(@"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]);
}];
Example of [NSMutableURLRequest setHTTPBodyStream]
NSData *imgData; UIImage *img; NSInputStream *stream;

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://my.url.com"]];

    for(int i=0; i<_dataContainer.count; i++)
    {
        @autoreleasepool {
            img = [UIImage imageWithCGImage:[[[_dataContainer objectAtIndex:i] defaultRepresentation]fullResolutionImage]];
            imgData = UIImageJPEGRepresentation(img, 1.0);
            stream = [[NSInputStream alloc] initWithData:imgData];
            [request setHTTPBodyStream:stream];
            [request setHTTPMethod:@"POST"];
            [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                                   completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                       NSLog(@"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]);
                                   }];
        }
    }