Sometimes when I try to inject JS script into UIWebView just after Facebook iOS login flow is completed, my iOS app gets frozen during fast-app-switch (from Safari to my app).
In the XCode console I get this error message:
failed to return after waiting 10 seconds. main run loop
mode:kCFRunLoopDefaultMode…
Sometimes the app doesn’t get frozen but the error message appears all the same.
I worked this around by running the JS injection code after an interval of 1 second. I implemented it as follows:
In the callback for FB session changes, I invoke my JS callback in 1 second using NSObject‘s performSelector:withObject:afterDelay: method. Here is my code sample:
/*
* Callback for session changes.
*/
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
if (!error) {
// We have a valid session
[self performSelector:@selector(jsCallback:) withObject:session afterDelay:1];
}
break;
// the rest of the method is omitted
}
- (void)jsCallback:(FBSession *)session {
UIWebView *webView = ...
NSString *jsScript = ...
[webView stringByEvaluatingJavaScriptFromString:jsScript];
}
It works but I’m concerned that it is not a reliable solution. For example, in some situations 1 second might not be enough.
Any ideas how to achieve the same effect in a more reliable way?
Well, it turned out to be simple. I made use of
UIApplicationState, like so:In
UIApplicationDelegate‘sapplicationDidBecomeActivemethod: