Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  56] [ 5]  / answers: 1 / hits: 84113  / 13 Years ago, tue, june 28, 2011, 12:00:00

When writing a iPhone / iPad app with a UIWebView, the console isn't visible.
this excellent answer shows how to trap errors, but I would like to use the console.log() as well.


More From » ios

 Answers
41

I have a solution to log, using javascript, to the apps debug console.
It's a bit crude, but it works.



First, we define the console.log() function in javascript, which opens and immediately removes an iframe with a ios-log: url.



// Debug
console = new Object();
console.log = function(log) {
var iframe = document.createElement(IFRAME);
iframe.setAttribute(src, ios-log:#iOS# + log);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
};
console.debug = console.log;
console.info = console.log;
console.warn = console.log;
console.error = console.log;


Now we have to catch this URL in the UIWebViewDelegate in the iOS app using the shouldStartLoadWithRequest function.



- (BOOL)webView:(UIWebView *)webView2 
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {

NSString *requestString = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
//NSLog(requestString);

if ([requestString hasPrefix:@ios-log:]) {
NSString* logString = [[requestString componentsSeparatedByString:@:#iOS#] objectAtIndex:1];
NSLog(@UIWebView console: %@, logString);
return NO;
}

return YES;
}

[#91454] Monday, June 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminkyrap

Total Points: 631
Total Questions: 89
Total Answers: 109

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
;