Possible crash with WKWebView

2.6k views Asked by At

I have a crash in my tweak and I believe it is happening somewhere in this function:

@implementation UIImage (RenderBatteryImage)

+ (UIImage *) renderBatteryImageForJS:(NSString *)javascript height:(CGFloat)height percentage:(int)percentage charging:(int)charging color:(UIColor *)color colorBg:(int)colorBg {
    int low = percentageIsLow(percentage);
    CGFloat r, g, b;
    [color getRed:&r green:&g blue:&b alpha:nil];
    __block UIImage *image;
    if([WKWebView class]) {
        NSLog(@"LITHIUM: Using WKWebView");
        WKWebView *newWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:[[WKWebViewConfiguration alloc] init]];
        [newWebView loadHTMLString:nil baseURL:nil];
        [newWebView evaluateJavaScript:[NSString stringWithFormat:@"(function%@)(%0.0f,%i,!!%i,!%i,[%0.0f,%0.0f,%0.0f],!%i)", javascript, height, percentage, charging, low, r, g, b, colorBg] completionHandler:^(NSString *imageData, NSError *error) {
            image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageData]] scale:[UIScreen mainScreen].scale];
        }];
        [newWebView release];
    }
    else {
        NSLog(@"LITHIUM: Using UIWebView");
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
        [webView loadHTMLString:nil baseURL:nil];
        image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"(function%@)(%0.0f,%i,!!%i,!%i,[%0.0f,%0.0f,%0.0f],!%i)", javascript, height, percentage, charging, low, r, g, b, colorBg]]]] scale:[UIScreen mainScreen].scale];
        [webView release];
    }
    return image;
}

@end

Note: I am not certain that this is the function causing the crash.

Looking through the syslog I can see LITHIUM: Using WKWebView logged before the crash, so I think the crash is happening within the first if statement.

Am I using WKWebView improperly here? Are there any other reasons this function could crash?

1

There are 1 answers

0
Fabio Ritrovato On BEST ANSWER

WKWebview evaluateJavaScript:completionHandler: is asynchronous, but you are releasing the webview immediately after creation. Also, even if it did't crash, you'd be returning a nil image since the completion block wouldn't be called before you exit the function.

I'm not sure what your trying to achieve, but you should either use the old UIWebview, or change your function to return void and use a completion block when done