HTTP-Anfrage über JavaScriptCore in iOS7
-
27-12-2019 - |
Frage
Ich versuche, eine der neuen Funktionen von iOS7 zu verwenden, das JavaScriptCore Framework.Ich kann erfolgreich einen „helloWorld“-String aus Javascript ausgeben, aber was mich interessiert, ist, HTTP-POSTs in Javascript durchzuführen und die Antwort dann an Objective-C zu übergeben.Leider, wenn ich ein erstelle XMLHttpRequest
Objekt in Javascript, bekomme ich EXC_BAD_ACCESS (code=1, address=....)
.
Hier ist der Javascript-Code (hello.js
):
var sendSamplePost = function () {
// when the following line is commented, everything works,
// if not, I get EXC_BAD_ACCESS (code=1, address=....)
var xmlHttp = new XMLHttpRequest();
};
var sayHello = function (name) {
return "Hello " + name + " from Javascript";
};
Hier ist der Objective-C-Code in meinem ViewController
:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
JSContext *context = [[JSContext alloc] initWithVirtualMachine:[[JSVirtualMachine alloc] init]];
NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"hello" ofType:@"js"];
NSLog(@"scriptPath: %@", scriptPath);
NSString *script = [NSString stringWithContentsOfFile:scriptPath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"script: %@", script);
[context evaluateScript:script];
JSValue *sayHelloFunction = context[@"sayHello"];
JSValue *returnedValue = [sayHelloFunction callWithArguments:@[@"iOS"]];
// this works!
self.label.text = [returnedValue toString];
JSValue *sendSamplePostFunction = context[@"sendSamplePost"];
// this doesn't work :(
[sendSamplePostFunction callWithArguments:@[]];
}
Könnte es sein, dass die HTTP-Anforderungsfunktionalität im JavaScriptCore Framework nicht bereitgestellt wird?Wenn ja, könnte ich das durch die Verwendung überwinden? UIWebView
'S -stringByEvaluatingJavaScriptFromString:
?Was wäre, wenn ich eine andere Javascript-Engine kompilieren und in mein Projekt einbinden würde (z. B.V8)?
Lösung
Ich vermute, dass HTTP-Anfragen nicht Teil von JavaScript Core sind, da sie tatsächlich Teil des Browsers und nicht der JavaScript-Sprache sind.
Ich gehe davon aus, dass der JavaScript-Kern nur das enthält, was in der ECMAScript-Definition enthalten ist.
Wenn Sie AJAX möchten, ist WebView die richtige Wahl.
Andere Tipps
XMLHttpRequest ist, wie bereits erwähnt, kein Teil von JavaScript, aber Sie können die iOS-URLRequest trotzdem umschließen, damit sie in Ihrem JS verfügbar ist.
in JSUtils.h
@protocol UtilsExport;
@interface JSUtils : NSObject <UtilsExport>
@end
@protocol UtilsExport <JSExport>
- (void)get:(NSString *)url then:(JSValue *)jsCallback;
@end
in JSUtils.m
#import "JSUtils.h"
- (void)get:(NSString *)url then:(JSValue *)callback {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10];
[request setHTTPMethod:@"GET"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] > 0 && error == nil) {
[callback callWithArguments:@[[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding], @YES]];
}
}];
}
Als nächstes binden Sie die Instanz an den JSContext irgendwo in Ihrem Code
JSContext *context = [[JSContext alloc] init];
context[@"utils"] = [[JSUtils alloc] init];
Aus Ihrer JS-Datei können Sie jetzt aufrufen
utils.getThen('http://localhost/api/dashboard', function(resultString){
console.log(resultString)
}
Sie können auch einen Block verwenden und ihn direkt an den JSContext binden, um das gleiche Ergebnis zu erzielen.
JSContext *context = [[JSContext alloc] init];
context[@"request"] = ^(NSString *url) {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:10];
NSURLResponse *response = nil;
[request setHTTPMethod:@"GET"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return body;
};
In JS:
var body = request(url);