Skip to content

Commit

Permalink
Added incremental XMLHttpRequest updates
Browse files Browse the repository at this point in the history
Summary:
@public

Previously, our XMLHttpRequest implementation would only update the readyState when the download was fully completed. This diff adds support for receiving incremental data updates as the download happens, which can be monitored by adding the onreadystatechange event handler.

As a performance optimization, incremental data updates are only sent if the onreadystatechanged handler has been set in the JS, otherwise it just sends the whole data block once download is complete, as before.

Test Plan:
* Run the UIExplorer XMLHttpRequest example (in both OSS and Catalyst) to see incremental downloads working.
* Run the Movies app to see regular (non-incremental) downloads in action
* Run any network-based app in Catalyst shell to verify RKDataManager still works
  • Loading branch information
nicklockwood committed Jun 5, 2015
1 parent bb95400 commit e00b9ac
Show file tree
Hide file tree
Showing 6 changed files with 366 additions and 74 deletions.
1 change: 1 addition & 0 deletions Examples/UIExplorer/UIExplorerList.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ var APIS = [
require('./StatusBarIOSExample'),
require('./TimerExample'),
require('./VibrationIOSExample'),
require('./XHRExample'),
];

var ds = new ListView.DataSource({
Expand Down
131 changes: 131 additions & 0 deletions Examples/UIExplorer/XHRExample.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';

var React = require('react-native');
var {
ProgressViewIOS,
StyleSheet,
View,
Text,
TouchableHighlight,
} = React;

class Downloader extends React.Component {

xhr: XMLHttpRequest;
cancelled: boolean;

constructor(props) {
super(props);
this.cancelled = false;
this.state = {
downloading: false,
contentSize: 1,
downloaded: 0,
};
}

download() {
this.xhr && this.xhr.abort();

var xhr = this.xhr || new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === xhr.HEADERS_RECEIVED) {
var contentSize = parseInt(xhr.getResponseHeader('Content-Length'), 10);
this.setState({
contentSize: contentSize,
downloaded: 0,
});
} else if (xhr.readyState === xhr.LOADING) {
this.setState({
downloaded: xhr.responseText.length,
});
} else if (xhr.readyState === xhr.DONE) {
this.setState({
downloading: false,
});
if (this.cancelled) {
this.cancelled = false;
return;
}
if (xhr.status === 200) {
alert('Download complete!');
} else if (xhr.status !== 0) {
alert('Error: Server returned HTTP status of ' + xhr.status + ' ' + xhr.responseText);
} else {
alert('Error: ' + xhr.responseText);
}
}
};
xhr.open('GET', 'http://www.gutenberg.org/cache/epub/100/pg100.txt');
xhr.send();
this.xhr = xhr;

this.setState({downloading: true});
}

componentWillUnmount() {
this.cancelled = true;
this.xhr && this.xhr.abort();
}

render() {
var button = this.state.downloading ? (
<View style={styles.wrapper}>
<View style={styles.button}>
<Text>Downloading...</Text>
</View>
</View>
) : (
<TouchableHighlight
style={styles.wrapper}
onPress={this.download.bind(this)}>
<View style={styles.button}>
<Text>Download 5MB Text File</Text>
</View>
</TouchableHighlight>
);

return (
<View>
{button}
<ProgressViewIOS progress={(this.state.downloaded / this.state.contentSize)}/>
</View>
);
}
}

exports.framework = 'React';
exports.title = 'XMLHttpRequest';
exports.description = 'XMLHttpRequest';
exports.examples = [{
title: 'File Download',
render() {
return <Downloader/>;
}
}];

var styles = StyleSheet.create({
wrapper: {
borderRadius: 5,
marginBottom: 5,
},
button: {
backgroundColor: '#eeeeee',
padding: 10,
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ function setUpAlert() {
var alertOpts = {
title: 'Alert',
message: '' + text,
buttons: [{'cancel': 'Okay'}],
buttons: [{'cancel': 'OK'}],
};
RCTAlertManager.alertWithArgs(alertOpts, null);
};
Expand Down
141 changes: 108 additions & 33 deletions Libraries/Network/RCTDataManager.m
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,21 @@

#import "RCTAssert.h"
#import "RCTConvert.h"
#import "RCTEventDispatcher.h"
#import "RCTLog.h"
#import "RCTUtils.h"

@interface RCTDataManager () <NSURLSessionDataDelegate>

@end

@implementation RCTDataManager
{
NSURLSession *_session;
NSOperationQueue *_callbackQueue;
}

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE()

Expand All @@ -24,6 +35,7 @@ @implementation RCTDataManager
*/
RCT_EXPORT_METHOD(queryData:(NSString *)queryType
withQuery:(NSDictionary *)query
sendIncrementalUpdates:(BOOL)incrementalUpdates
responseSender:(RCTResponseSenderBlock)responseSender)
{
if ([queryType isEqualToString:@"http"]) {
Expand All @@ -35,41 +47,30 @@ @implementation RCTDataManager
request.allHTTPHeaderFields = [RCTConvert NSDictionary:query[@"headers"]];
request.HTTPBody = [RCTConvert NSData:query[@"data"]];

// Build data task
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *connectionError) {

NSHTTPURLResponse *httpResponse = nil;
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
// Might be a local file request
httpResponse = (NSHTTPURLResponse *)response;
}

// Build response
NSArray *responseJSON;
if (connectionError == nil) {
NSStringEncoding encoding = NSUTF8StringEncoding;
if (response.textEncodingName) {
CFStringEncoding cfEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
encoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
// Create session if one doesn't already exist
if (!_session) {
_callbackQueue = [[NSOperationQueue alloc] init];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:configuration
delegate:self
delegateQueue:_callbackQueue];
}

__block NSURLSessionDataTask *task;
if (incrementalUpdates) {
task = [_session dataTaskWithRequest:request];
} else {
task = [_session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
RCTSendResponseEvent(_bridge, task);
if (!error) {
RCTSendDataEvent(_bridge, task, data);
}
responseJSON = @[
@(httpResponse.statusCode ?: 200),
httpResponse.allHeaderFields ?: @{},
[[NSString alloc] initWithData:data encoding:encoding] ?: @"",
];
} else {
responseJSON = @[
@(httpResponse.statusCode),
httpResponse.allHeaderFields ?: @{},
connectionError.localizedDescription ?: [NSNull null],
];
}

// Send response (won't be sent on same thread as caller)
responseSender(responseJSON);

}];
RCTSendCompletionEvent(_bridge, task, error);
}];
}

// Build data task
responseSender(@[@(task.taskIdentifier)]);
[task resume];

} else {
Expand All @@ -78,4 +79,78 @@ @implementation RCTDataManager
}
}

#pragma mark - URLSession delegate

- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)task
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
RCTSendResponseEvent(_bridge, task);
completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)task
didReceiveData:(NSData *)data
{
RCTSendDataEvent(_bridge, task, data);
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
RCTSendCompletionEvent(_bridge, task, error);
}

#pragma mark - Build responses

static void RCTSendResponseEvent(RCTBridge *bridge, NSURLSessionTask *task)
{
NSURLResponse *response = task.response;
NSHTTPURLResponse *httpResponse = nil;
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
// Might be a local file request
httpResponse = (NSHTTPURLResponse *)response;
}

NSArray *responseJSON = @[@(task.taskIdentifier),
@(httpResponse.statusCode ?: 200),
httpResponse.allHeaderFields ?: @{},
];

[bridge.eventDispatcher sendDeviceEventWithName:@"didReceiveNetworkResponse"
body:responseJSON];
}

static void RCTSendDataEvent(RCTBridge *bridge, NSURLSessionDataTask *task, NSData *data)
{
// Get text encoding
NSURLResponse *response = task.response;
NSStringEncoding encoding = NSUTF8StringEncoding;
if (response.textEncodingName) {
CFStringEncoding cfEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
encoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
}

NSString *responseText = [[NSString alloc] initWithData:data encoding:encoding];
if (!responseText && data.length) {
RCTLogError(@"Received data was invalid.");
return;
}

NSArray *responseJSON = @[@(task.taskIdentifier), responseText ?: @""];
[bridge.eventDispatcher sendDeviceEventWithName:@"didReceiveNetworkData"
body:responseJSON];
}

static void RCTSendCompletionEvent(RCTBridge *bridge, NSURLSessionTask *task, NSError *error)
{
NSArray *responseJSON = @[@(task.taskIdentifier),
error.localizedDescription ?: [NSNull null],
];

[bridge.eventDispatcher sendDeviceEventWithName:@"didCompleteNetworkResponse"
body:responseJSON];
}

@end
Loading

0 comments on commit e00b9ac

Please sign in to comment.