Carpe diem (Felix's blog)

I am a happy developer

Debug UIWebView in Your iOS App

It is often to embed a UIWebView in an iOS app. However it doesn’t provide the powerful webkit inspector by default. Nathan de Vries has written a post to solve the problem, but the solution didn’t work on my XCode 4 with Clang front end.

This is Nathan’s solution:

Nathan’s solution
1
2
3
4
5
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // ...Snipped...
    [NSClassFromString(@"WebView") _enableRemoteInspector];
    // ...Snipped...
}

The compiler will complain that you can’t force WebView to perform private method _enableRemoteInspector. Thus, I use performSelector:@selector() instead of direct method call. Guess what? The compiler accept the hack. Awesome!

1
2
3
4
5
6
7
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // enable the hack only when we use simulator
#if (TARGET_IPHONE_SIMULATOR)
    [NSClassFromString(@"WebView") performSelector:@selector(_enableRemoteInspector)];
#endif
    // ...Snipped...
}

Now simply run your iphone simulator and open the url localhost:9999 to view your inspector. Voilà!

Edit

brainlock shared his remote inspector that can use proxy to debug on the device. However, I prefer to use simple and stupid solution after all. ;)

For more curious, The #if (TARGET_IPHONE_SIMULATOR) macro will ensure the hack of accessing WebKit’s private api won’t ship with your production code.

Comments