iOS HybirdApp入門 基于PhoneGap

  1. 首先打開命令行敲上$ sudo npm install -g phonegap然后回車
  2. (推薦)輸入密碼后,PhoneGap就會自動安裝.
    也可以到http://phonegap.com/install/ 這里來下載最新的PhoneGap2.9.1(雖然我下載后也搞不懂,運(yùn)行過程序后沒發(fā)覺有明顯變化)
  3. 然后我們就可以來新建項(xiàng)目了
  • 新建項(xiàng)目也有兩種方法,第一種是按照官網(wǎng)上的
$ phonegap create myFirstHybird
$ cd myFirstHybird
$ phonegap run ios
  • 敲完命令以后就可以發(fā)現(xiàn)myFirstHybird目錄下有這些文件了,可以看到platforms目錄下有ios然后有個helloWord的工程,雙擊運(yùn)行就ok了.


    目錄

    運(yùn)行的程序
  • 這種方法有個不好的地方就是你的工程名永遠(yuǎn)都是helloWord

  • 下面來介紹第二種方法
    1.首先要安裝cordova sudo npm install -g cordova
    2.在想要新建項(xiàng)目的文件夾中打開命令行,敲入cordova create theSecond com.ozx theSecondPro theSecond文件夾名,com.ozx:Bundle Identifier theSecondPro:工程名
    3.按回車以后,就回自動生成文件,但是沒有ios代碼,platforms還是空的,現(xiàn)在我們來為它添加ios平臺代碼,在終端輸入:cordova platform add ios , 打開工程就有
    項(xiàng)目

    4.運(yùn)行,運(yùn)行效果與方法一相同
    那么如何修改js中的代碼呢,我們現(xiàn)在開始來探討.

點(diǎn)開Staging文件夾,對index.html進(jìn)行修改

<!DOCTYPE HTML>
<html>
    <head>
        <title>PhoneGap</title>
        <script type="text/javascript" charset="utf-8" src=\'#\'" /span>
            </script>
            <script type="text/javascript" charset="utf-8" src=\'#\'" /span>
            </script>
        
        <script type="text/javascript" charset="UTF-8">
            
            function loadURL(url) {
                var iFrame;
                iFrame = document.createElement("iframe");
                iFrame.setAttribute("src", url);
                iFrame.setAttribute("style", "display:none;");
                iFrame.setAttribute("height", "0px");
                iFrame.setAttribute("width", "0px");
                iFrame.setAttribute("frameborder", "0");
                document.body.appendChild(iFrame);
                iFrame.parentNode.removeChild(iFrame);
                iFrame = null;
            }
        function check() {
            loadURL("youdao:abc");
        }

        </script>
    </head>
    <body>
        <br/>
        <br/>
        <br/>
        <input type="button" value="add" onclick="check();" />
    </body>
</html>

在CDVViewController.m文件中找到- (BOOL)webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
在其中添加

if ([[url scheme] isEqualToString:@"youdao"]) {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"test" message:[url absoluteString] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] ;
        [alertView show];
        return NO;
    }

那么這樣native(oc)就可以處理js上發(fā)送過來的請求了.
而native如何注入js代碼呢

- (IBAction)add:(id)sender {
    NSString * js = @" var p = document.createElement('p'); p.innerText = 'new Line';document.body.appendChild(p);";
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

這樣就可以在webview中顯示新添加的內(nèi)容了.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容