標籤: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