【问题标题】:How to load page content within a new UIWebView before exiting current method如何在退出当前方法之前在新的 UIWebView 中加载页面内容
【发布时间】:2014-11-26 13:17:51
【问题描述】:

我有一个已实现本地服务器的应用程序,它处理来自 Web 前端的请求。 UIWebView 呈现一些 GUI,用户进行一些交互,我处理他的请求并将响应发送回 webview。

有时我会收到一些请求,需要打开第二个 web 视图(例如用于 facebook 登录)并在当前方法中等待结果从第二个 web 视图返回。

当我在具有双核处理器的 iDevice 上运行这种情况时,它按预期工作。 但是当我在单核 iPhone 4 上运行它时,webview 处理会被阻止,直到我离开当前方法(带有等待指示符的白页)。

我通过为当前线程设置睡眠来解决这个问题,这样主线程就有时间处理他的运行循环中的事件(如果我正确理解的话)

 - (void)requestProcessingMethod { // <-- on background thread
       someCalculations ...

       dispatch_sync(dispatch_get_main_queue(), ^{
       [self displayFacebookLoginWebView];
       });

       while(!facebookReturnCondition){
           [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
           [NSThread sleepForTimeInterval:0.5]; // <-- on single core without this
                                                //     facebook webview will not load the login page
       }

       return response; //
   }

我对此不满意。为睡眠设置线程看起来很糟糕。

有没有办法在不退出当前方法(后台线程)的情况下从后台线程添加工作 UIWebView?

或者是否可以手动切换/强制运行循环执行?

【问题讨论】:

    标签: ios objective-c iphone uiwebview nsrunloop


    【解决方案1】:

    现在我不确定这是否可行,目前无法测试。但是:

    您可以尝试使用操作依赖项将操作作为队列中的单独操作。

    当你使用这种方法时:

    -(void)methodThatCallsRequestProcessingMethod {
    
       NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
       NSInvocationOperation* theMainThreadOp = [[NSInvocationOperation alloc] initWithTarget:self
                        selector:@selector(displayFacebookLoginWebView) object:nil];
    
       NSInvocationOperation* theOp = [[NSInvocationOperation alloc] initWithTarget:self
                        selector:@selector(requestProcessingMethod) object:nil];
       [theOp addDependency: theMainThreadOp];
    
       [[NSOperationQueue mainQueue] addOperation: theMainThreadOp];
       [queue addOperation:theOp];
    
    }
    

    通过阅读并发指南,您似乎可以对不同的队列有操作依赖关系。这意味着您可以确保 UI 在主线程中运行,Web 稍后在异步线程中运行,从而在所有设备上保持主线程清晰和响应。

    Apple Concurrency Guide

    【讨论】:

      猜你喜欢
      • 2014-07-21
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-30
      • 2013-01-22
      相关资源
      最近更新 更多