webView與OC的互動

來源:互聯網
上載者:User

標籤:

layout: post
title: webView 的 iOS 與 js 互動
subtitle: iOS 與 js 互動的幾種方式
author: manajay
date: 2016-05-31 16:17:13 +0800
categories: webView js

tag: web 1. web 給 原生 傳遞資料
  • web 網頁的原始碼
var res = {"title":" 端午禮包提回去,丈母娘不滿意來找我!!!","url":"http:\/\/app.xxx.com\/news\/rd\/content_wap_39865.shtml","image":"http:\/\/www.xxx.com\/v\/b\/images\/2016\/5\/30\/20165301464599344828_167.jpg","summary":" 端午禮包提回去,丈母娘不滿意來找我!!!"};function item_info(){    return JSON.stringify(res);}try {    window.share.shareData(JSON.stringify(res));} catch(e) {}
  • 在 webView 的 - (void) webViewDidFinishLoad:(UIWebView *)webView 方法中 擷取
// 使用 stringByEvaluatingJavaScriptFromString 調用 js 方法NSString *info = [webView stringByEvaluatingJavaScriptFromString:@"item_info()"];NSDictionary *shareData = [NSJSONSerialization JSONObjectWithData:[info dataUsingEncoding:NSUnicodeStringEncoding] options:NSJSONReadingAllowFragments error:nil];
2. Web 調用 原生的功能

主要是 使用 自訂協議頭
在 web 中的按鈕 或者 點選連結的中 寫一個方法function, 然後調用 類似

window.location.href=‘playvideo://tide?url=http://123.125.148.27:96/video/gesila.mp4‘;"

其中 playvideo:// 為自訂的協議頭

然後原生代碼中,使用 webView 的代理方法 即 重定義技術

- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType NSURL *url = request.URL;    if ([url.scheme isEqualToString:@"playvideo"]) {        NSArray *querys = [url.query componentsSeparatedByString:@"&"];        NSString *videoUrl = nil;        for (NSString *query in querys) {            if ([query rangeOfString:@"url="].location != NSNotFound) {                videoUrl = [query substringFromIndex:4];                break;            }        }使用 & 分割 想要傳遞的資料參數 就可以了

webView與OC的互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.