Registering a custom URL Scheme in Mac and iOS
JAN 10TH, 2012
URL scheme is similar http://
to ftp://
something like this, afp://
usually with a transport protocol as the URL scheme. But in fact, you can register any type of URL Scheme in iOS and Mac. When a user accesses your custom URL scheme link in a browser, the operating system opens your program to respond to the request.
It is easy to register a custom URL scheme in your program. There are two main steps: Add the URL Scheme you need to register in the program's Info.plist, and then add the code that handles such requests in your application.
The first step is exactly the same for both iOS and Mac applications. Here's how:
In Info.plist
, add a field with the name CFBundleURLTypes
(URL Types). Xcode will automatically create a necessary key for you: URL Identifier
(cfbundleurlname), the value of this key can be assigned to a unique string. is usually the reverse domain name structure, such as: me.venj.myapp
. Then add a subkey under the URL types: CFBundleURLSchemes
(URL schemes), fill in the name of the URL scheme you want to register, such as: cloud
. You can add multiple URL Scheme.
The following is an example of an XML structure:
123456789 |
<key>cfbundleurltypes</ Key><array> <dict><key>cfbundleurlname</key> <string>me.venj.myapp</string> < Key>cfbundleurlschemes</key> <array><string>cloud</string> </array> </dict> </ARRAY>
|
In this way, we can process the request in the program. Let's take a look at the processing methods under iOS and Mac separately:
Ios:
In iOS, we can add a method to the appdelegate to handle this request. For iOS 4.1 or earlier systems, use the -application:handleOpenURL:
method for system use after iOS 4.2: -application:openURL:sourceApplication:annotation:
method.
Here is the sample code:
123456789 |
/* For IOS 4.1 and earlier */-(BOOL)Application:(UIApplication*)ApplicationHandleopenurl:(Nsurl*)Url{ Handle URL request. Uialertview*Alert=[[UialertviewAlloc]Initwithtitle:@ "URL Request"Message[UrlAbsolutestring]DelegateNilCancelbuttontitle:@ "OK"Otherbuttontitles:Nil]; [AlertShow]; ReturnYES;}/* for IOS 4.2 and later */-(BOOL)Application:(UIApplication*)ApplicationOpenURL:(Nsurl*)UrlSourceapplication:(NSString*)SourceapplicationAnnotation(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; /span>
|
Our demo program simply shows one UIAlertView
to respond to the request. What to do with the actual situation depends on the need.
The effect is as follows:
"Go" register your custom URL Scheme in Mac and iOS