2012-11-16 47 views
0

有時,當我嘗試在Facebook iOS登錄流程完成後將JS腳本注入UIWebView時,我的iOS應用程序在fast-app-switch(從Safari到我的應用程序)。
在XCode控制檯中,我收到以下錯誤消息:在iOS iOS登錄流程完成後將JS腳本注入UIWebView

等待10秒後未能返回。主運行的循環 模式:kCFRunLoopDefaultMode ...

有時應用程序沒有得到凍結,但仍然出現錯誤信息都是一樣的。

我通過在1秒的時間間隔後運行JS注入代碼來解決這個問題。我實現它如下:

在FB會話更改的回調中,我使用NSObjectperformSelector:withObject:afterDelay:方法在1秒內調用我的JS回調。這裏是我的代碼示例:

/* 
* 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]; 
} 

它的工作原理,但我擔心它不是一個可靠的解決方案。例如,在某些情況下1秒可能不夠。

任何想法如何以更可靠的方式實現相同的效果?

回答

0

那麼,事實證明這很簡單。我利用了UIApplicationState,就像這樣:

/* 
* 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 
     UIApplicationState appState = [[UIApplication sharedApplication] applicationState]; 

     NSLog(@"We have a valid session, app state: %u",appState); 

     if (UIApplicationStateActive == appState){ 
      [self jsCallback:session]; 
     } else { 
      self.fbSessionJustOpened = YES; 
     } 
     } 
    break; 

    // the rest of the method is omitted 
} 

UIApplicationDelegateapplicationDidBecomeActive方法:

- (void)applicationDidBecomeActive:(UIApplication *)application 
{ 
    if (self.isFbSessionJustOpened){ 
     self.fbSessionJustOpened = NO; // reset flag to NO   
     [self jsCallback:[FBSession activeSession]]; 
    } 
}