【轉】在Mac和iOS中註冊自訂的URL Scheme

來源:互聯網
上載者:User

標籤:http   io   ar   os   使用   for   sp   strong   div   

在Mac和iOS中註冊自訂的URL Scheme

JAN 10TH, 2012

URL Scheme是類似http://ftp://afp://這樣的東西,通常是用傳輸協議作為URL Scheme。不過事實上,你可以在iOS和Mac中註冊任何類型的URL Scheme。當使用者在瀏覽器中訪問你的自訂URL Scheme的連結的時候,作業系統就會開啟你的程式,響應這個請求。

要在程式中註冊自訂URL Scheme非常簡單。主要分為兩個步驟:在程式的Info.plist中加入你需要註冊的URL Scheme,然後在你的應用程式中加入處理這類請求的代碼。

其中,第一個步驟對於iOS和Mac應用程式來說是完全相同的。方法如下:

Info.plist中,增加一個欄位,名稱為CFBundleURLTypes(URL Types)。Xcode會自動為你建立一個必須的鍵:URL Identifier(CFBundleURLName),這個鍵的值可以賦值為一個唯一的字串。通常是逆向的網域名稱結構,如:me.venj.myapp。然後在URL Types這個鍵下增加一個子項:CFBundleURLSchemes(URL Schemes),這裡填入你想註冊的URL Scheme的名稱,如:cloud。你可以增加多個URL Scheme。

下面是一個樣本的XML結構:

1234567891011
<key>CFBundleURLTypes</key><array>    <dict>        <key>CFBundleURLName</key>        <string>me.venj.myapp</string>        <key>CFBundleURLSchemes</key>        <array>            <string>cloud</string>        </array>    </dict></array>

這樣,我們就可以在程式中處理請求了。下面我們來分別看一下iOS和Mac下的處理方法:

iOS:

在iOS中,我們可以在AppDelegate中加入一個方法,來處理這個請求。對於iOS 4.1或更早的系統,使用-application:handleOpenURL:方法,對於iOS 4.2以後的系統使用:-application:openURL:sourceApplication:annotation:方法。

下面是範例程式碼:

1234567891011121314151617
/* For iOS 4.1 and earlier */- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {    // Handle url request.    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"URL Request" message:[url absoluteString] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];    [alert show];    return YES;}/* For iOS 4.2 and later */- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {    // Handle url request.    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"URL Request" message:[url absoluteString] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];    [alert show];    return YES;}

我們的示範程式只是簡單的顯示了一個UIAlertView來響應請求。實際應該如何處理那就看需要了。

效果如下:

【轉】在Mac和iOS中註冊自訂的URL Scheme

聯繫我們

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