Objective-c與js相互調用及傳參數注意

來源:互聯網
上載者:User

1、Objective-c調用js方法,只是需要調用uiwebview內建的方法就可以了。

                [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"getHtmlString(‘%@’)",htmlStr]];

2、js調用Objective-c方法,這時就需要和js約定一個參數或者方法了。

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

在這個回調方法中,我們會得到伺服器傳過來的資料request,我們可以判斷穿過來的參數,然後進行判斷調用oc的方法。

            if ([request.URL.scheme isEqualToString:@"gethtmlstring"]) {                                NSString *htmlStr = [self getHtmlString:description];                htmlStr =  [htmlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];                [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"getHtmlString(\"%@\")",htmlStr]];            }

這樣就實現了對oc的調用了。

在這裡特別值得注意的問題:我這裡傳了html格式的參數。我在這裡就遇到了,傳過去的參數始終不對,無法調用js的方法。

stringWithContentsOfFile,這個方法用來讀取檔案,如果不指定編碼方式的話,有可能造成資料的丟失,所以我這裡指定了utf-8的編碼方式。 在傳參數的時,還有可能的一種問題。這個參數裡面如果帶有(\r \n ')等等, js那邊收不到這個值, 這些帶\的需要轉義, 如下這麼寫js才能收到完整的訊息:

message = [message stringByReplacingOccurrencesOfString:@"\n" withString:@"\\\\n"];NSString *jsMethod  = [NSString stringWithFormat:@"JsMethod(\"%@\")", message]

例子代碼:http://download.csdn.net/detail/pearlhuzhu/5550141

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.