Created
July 3, 2013 07:08
-
-
Save beccadax/5916002 to your computer and use it in GitHub Desktop.
A category on UIWebView that lets you return any JSON-compatible content from Javascript code. (This means arrays, objects/dictionaries, strings, numbers, and nulls.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UIWebView+JSONObjectByEvaluatingJavascript.h | |
// Feeder | |
// | |
// Created by Brent Royal-Gordon on 7/1/13. | |
// Copyright (c) 2013 Architechies. All rights reserved. | |
// | |
@interface UIWebView (Additions) | |
- (id)JSONObjectByEvaluatingJavascript:(NSString*)javascript parameters:(NSDictionary*)params options:(NSJSONReadingOptions)options; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UIWebView+JSONObjectByEvaluatingJavascript.m | |
// Feeder | |
// | |
// Created by Brent Royal-Gordon on 7/1/13. | |
// Copyright (c) 2013 Architechies. All rights reserved. | |
// | |
@implementation UIWebView (JSONObjectByEvaluatingJavascript) | |
- (id)JSONObjectByEvaluatingJavascript:(NSString*)javascript parameters:(NSDictionary*)params options:(NSJSONReadingOptions)options { | |
NSArray * keys = params.allKeys ?: @[]; | |
NSArray * values = [params objectsForKeys:keys notFoundMarker:[NSNull null]] ?: @[]; | |
NSString * parameterNames = [keys componentsJoinedByString:@", "]; | |
NSData * parameterData = [NSJSONSerialization dataWithJSONObject:values options:0 error:NULL]; | |
NSString * parameterValues = [[NSString alloc] initWithData:parameterData encoding:NSUTF8StringEncoding]; | |
javascript = [NSString stringWithFormat:@"JSON.stringify((function(%@) { %@ }).apply(window, %@))", parameterNames, javascript, parameterValues]; | |
NSString * jsonString = [self stringByEvaluatingJavaScriptFromString:javascript]; | |
NSData * jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; | |
return [NSJSONSerialization JSONObjectWithData:jsonData options:options|NSJSONReadingAllowFragments error:NULL]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment