xcode 如何在 IOS 中的 webview 中检查响应类型(Json/Html)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36257893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:40:48  来源:igfitidea点击:

how to check the response type(Json/Html) in webview in IOS

iosxcodewebview

提问by Shripad Desai

I have a web view which request one web page, now that web has some action events which may reply to IOS app as HTML or json. So how would the app will come to know the response type sent. So that the response is handled within the app.

我有一个请求一个网页的 web 视图,现在该 web 有一些动作事件可以作为 HTML 或 json 回复 IOS 应用程序。那么应用程序将如何知道发送的响应类型。以便在应用程序内处理响应。

Reading of static HTML content in webview using its delegate is what i have tried, when it is dynamic then how can one handle.

使用其委托在 webview 中读取静态 HTML 内容是我尝试过的,当它是动态的时,如何处理。

code logic:-

代码逻辑:-

  1. ON load of controller, request page with URL(something) in web view, user will interact
  2. check response type if JSON then 4 else 3
  3. load web page with different URL
  4. Deserialize the JSON Data and store in native DB
  1. 在控制器加载时,在 web 视图中请求带有 URL(something) 的页面,用户将进行交互
  2. 检查响应类型 if JSON then 4 else 3
  3. 加载具有不同 URL 的网页
  4. 反序列化 JSON 数据并存储在本机数据库中

回答by UditS

Method 1

方法一

First, You need to set and handle the UIWebViewdelegate methods in your UIViewController

首先,您需要设置和处理UIWebView您的委托方法UIViewController

Then, in webView: shouldStartLoadWithRequest: navigationType:method, use the following

然后,在webView: shouldStartLoadWithRequest: navigationType:方法中,使用以下

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

    NSError *error;
    NSString *responseString = [NSString stringWithContentsOfURL:request.URL
                                                        encoding:NSASCIIStringEncoding
                                                           error:&error];

    //Parse the string here to confirm if it's JSON or HTML
    //In case of JSON, stop the loading of UIWebview
    if(json) {
        retrun NO;
    }

    return YES;
}

Note:This will take a performance hit in case of HTML content as the response will be loaded 2 times. Once in stringWithContentsOfURLmethod and second time when the web view loads.

注意:在 HTML 内容的情况下,这会影响性能,因为响应将被加载 2 次。在stringWithContentsOfURL方法中一次,在 web 视图加载时第二次。

Method 2

方法二

To avoid the double loading you can let the web view load, irrespective of the content type. And then get the loaded content in webViewDidFinishLoadmethod.

为了避免双重加载,无论内容类型如何,您都可以让 web 视图加载。然后在webViewDidFinishLoad方法中获取加载的内容。

For this you may need to perform some changes on the server end as well.

为此,您可能还需要在服务器端执行一些更改。

Suppose your HTML page with JSON is structured as :

假设您使用 JSON 的 HTML 页面的结构如下:

<html>
<body>

<div id="json" style="display: none">{"jsonvalue":"{{result}}"}</div>

</body>
</html>

Then in webViewDidFinishLoad

然后在 webViewDidFinishLoad

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *res = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('json').innerHTML"];

    //Use the JSON string as required
}

回答by Sachin Tyagi

After the long brainstorming as i am new to IOS, I figure out the solution for swift as I could not find the solution in swift language. Here are the few steps for solutions-

由于我是 IOS 新手,经过长时间的头脑风暴,我找到了 swift 的解决方案,因为我找不到 swift 语言的解决方案。以下是解决方案的几个步骤-

  1. First drag and drop the webView to create the connection of webview

    @IBOutlet weak var webViewlLoad: UIWebView!

  2. Now load your webView by calling

    webViewlLoad.loadRequest(URL)

  3. Now wait for some time and check the webview for getting the data by the following code

  1. 先拖拽webView,创建webview的连接

    @IBOutlet 弱变量 webViewlLoad:UIWebView!

  2. 现在通过调用加载您的 webView

    webViewlLoad.loadRequest(URL)

  3. 现在等待一段时间,通过以下代码检查webview获取数据

    let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 5 * Int64(NSEC_PER_SEC))

    dispatch_after(time, dispatch_get_main_queue()) {

 //put your code which should be executed with a delay here

     let doc = self.webViewlLoad.stringByEvaluatingJavaScriptFromString("document.documentElement.outerHTML")!

    print("document JSON  = \(doc)")

    let startIndexJSON  = doc.rangeOfString("{")?.startIndex

    let endIndexJSON  = doc.rangeOfString("}}")?.startIndex

    var finalJson =   doc.substringWithRange( Range<String.Index>(start:startIndexJSON!, end: endIndexJSON!.advancedBy(2)))     
    print("\n\n finalJson JSON  = \(finalJson)")

  }
    let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 5 * Int64(NSEC_PER_SEC))

    dispatch_after(time, dispatch_get_main_queue()) {

 //put your code which should be executed with a delay here

     let doc = self.webViewlLoad.stringByEvaluatingJavaScriptFromString("document.documentElement.outerHTML")!

    print("document JSON  = \(doc)")

    let startIndexJSON  = doc.rangeOfString("{")?.startIndex

    let endIndexJSON  = doc.rangeOfString("}}")?.startIndex

    var finalJson =   doc.substringWithRange( Range<String.Index>(start:startIndexJSON!, end: endIndexJSON!.advancedBy(2)))     
    print("\n\n finalJson JSON  = \(finalJson)")

  }

In above code i wait for 5 seconds , then the webView load the json. I read it by substring the result.

在上面的代码中,我等待 5 秒,然后 webView 加载 json。我通过子串结果读取它。