iOS SDK: Working with URL Schemes

iOS SDKMobile DevelopmentCommunication between apps provides your application with an opportunity to take advantage of other application's functionality, send and receive data between apps, and provide a rich user experience that “just works".In this tutorial we are going to create two apps, one app that sends data, and another app that receives that data. Together, these apps will demonstrate URL schemes, a method for sending and receiving data between applications. This is a fairly advanced tutorial with regard to understanding Xcode, and I would highly recommend that before you begin this tutorial you feel comfortable using Xcode and Interface Builder.Please note: A physical device is required for testing this app.Step 1: Creating a Sender ProjectLet's go ahead and create a new Xcode project, select “View Based Application." Hit next. Name the project “Sender" and enter your Company Identifier. This project will house the app that sends information to the “Receiver" app which we will create shortly.Create a Sender ProjectStep 2: Setup the XIB and Interface Builder ConnectionsBefore we setup our XIB, we'll create a few declarations ahead of time.In the left Navigator Pane, open up SenderViewController.h and set it up like this:01020304050607080910111213#import@interface SenderViewController : UIViewController {? ? IBOutlet UITextField *textBox;} -(IBAction) openMaps:(id)sender;-(IBAction) openYoutube:(id)sender;-(IBAction) openReceiverApp:(id)sender; @property(nonatomic, retain) IBOutlet UITextField *textBox; @endBy doing this, we are declaring a few methods which will be called by UIButtons in the future and a variable that references a UITextField. These UI Elements will be added next.Now, in the left Navigator Pane, open up SenderViewController.xib and drag out one UITextField and three UIButtons from the right-hand side Utilities Pane. Stack them vertically on the view and rename the first button to “Send Text to Receiver App ", the second button to “Open Maps", and the third button to “Open YouTube". Your view should resemble something similar the image below.Sender View XIBNow, our last step is to finalize our IBConnections. Select File's Owner (the orange wireframe box) on the left and then, in the Utilities Pane on the right, choose the Connections Inspector (the arrow) tab. Connect textBox to the UITextField. Next, connect openMaps:, openYoutube:, and openReceiverApp: to their respective button's “Touch Up Inside" event by a connection line from the circle on the right to the buttons. The connections should resemble what is shown below.Sender XIB Interface Builder ConnectionsStep 3: Opening URLs for CommunicationTo begin, open the file SenderViewController.m from the Navigator Pane. Under @implementation add the following line to synthesize our property:1@synthesize textBox;Let's also make sure we follow correct memory management rules and cleanup the retain we had in our property, above [super dealloc]; add:1[textBox release];Lastly, in our viewDidUnload method below “[super viewDidUnload];" add:1self.textBox = nil;A brief rundown of URL schemes is that URL schemes allow apps to register their own protocol to allow the transfer of data. Some common examples of protocols you may use on a regular basis are, “http://", “https://", and “ftp://". For example a bookmarking app may want to register “bookmark://", so other apps could bookmark links using the URL scheme, “bookmark://www.envato.com". Apps cannot register to the “http://" protocol, although some Apple apps break this rule and are registered “http://" to open up apps like Maps, iTunes, and YouTube. Our Receiver app will register for “readtext://texthere". We can open these URL's by calling UIApplication's method openURL:. When we use openURL: it will launch the specified app and hand it the data you provided.Add the following methods to your SenderViewController.m file:010203040506070809101112131415161718192021222324252627282930313233-(IBAction) openMaps:(id)sender {? ? // Opens a map containing Envato's Headquarters? ? UIApplication *ourApplication = [UIApplication sharedApplication];? ? NSString *ourPath = @"http://maps.google.com/maps?ll=-37.812022,144.969277";? ? NSURL *ourURL = [NSURL URLWithString:ourPath];? ? [ourApplication openURL:ourURL];} -(IBAction) openYoutube:(id)sender {? ? // Opens a video of an iPad 2 Commercial? ? UIApplication *ourApplication = [UIApplication sharedApplication];? ? NSString *ourPath = @"http://www.youtube.com/watch?v=TFFkK2SmPg4";? ? NSURL *ourURL = [NSURL URLWithString:ourPath];? ? [ourApplication openURL:ourURL];} -(IBAction) openReceiverApp:(id)sender {? ? // Opens the Receiver app if installed, otherwise displays an error? ? UIApplication *ourApplication = [UIApplication sharedApplication];? ? NSString *URLEncodedText = [self.textBox.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];? ? NSString *ourPath = [@"readtext://" stringByAppendingString:URLEncodedText];? ? NSURL *ourURL = [NSURL URLWithString:ourPath];? ? if ([ourApplication canOpenURL:ourURL]) {? ? ? ? [ourApplication openURL:ourURL];? ? }? ? else {? ? ? ? //Display error? ? ? ? UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Receiver Not Found" message:@"The Receiver App is not installed. It must be installed to send text." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];? ? ? ? [alertView show];? ? ? ? [alertView release];? ? } }These methods are using the openURL method of the UIApplication to send data to other apps. Apple has registered the Maps application and YouTube application with “http://" essentially, so we simply call openURL on those URLs. To create our URL, we also used the stringByAddingPercentEscapesUsingEncoding: method to ensure the string is a valid URL by URL encoding the string (we will decode it in our Receiver app). For our custom URL “readtext://" we first check if the link can be opened with canOpenURL. This essentially checks whether the app that is registered to that particular URL scheme is installed, and if it is, we are able to open the URL with our text. If the app is not installed, we display an error message. Remember that when you release your app to the public, the URL scheme your app is dependent on might not work because the other app isn't installed. You should always perform the canOpenURL when opening non-http:// URL schemes.Go ahead and build and run the application. Notice the Maps and YouTube buttons open up their respective apps. Also, the “Sent Text" button returns an error message since we have yet to create our “Receiver" app.Step 4: Creating a Receiver AppCreate a new XCode project, and select “View Based Application." Hit next. Name the project “Receiver" and enter your Company Identifier. This project will house the app that reads information sent by the “Sender" app.Create a Receiver ProjectStep 5: Register the Custom URL SchemeIn the Project Navigator, expand the Supporting Files group and open the Receiver-Info.plist file.You can add a new row by going to the menu and clicking Editor > Add Item. Set up a URL Types item by adding a new item. Expand the URL Types key, expand Item 0, and add a new item, “URL schemes". Fill in “readtext" for Item 0 of “URL schemes" and your company identifier for the “URL Identifier". Your file should resemble the image below when done.Receiver-Info.plistStep 6 : Handle the URLOpen ReceiverAppDelegate.m and replace the application:applicationDidFinishLaunchingWithOptions: method with the following code:0102030405060708091011121314151617- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{? ? // Override point for customization after application launch.? ? self.window.rootViewController = self.viewController;? ? [self.window makeKeyAndVisible];? ? //Display error is there is no URL? ? if (![launchOptions objectForKey:UIApplicationLaunchOptionsURLKey]) {? ? ? ? UIAlertView *alertView;? ? ? ? alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"This app was launched without any text. Open this app using the Sender app to send text." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];? ? ? ? [alertView show];? ? ? ? [alertView release];? ? }? ? return YES;}This alerts an error if the application is opened without a URL. Generally, if this occurs you would load your app normally but for the sake of experimenting we will display an error.Add the following code beneath the application:applicationDidFinishLaunchingWithOptions: method.01020304050607080910- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {? ? // Display text? ? UIAlertView *alertView;? ? NSString *text = [[url host] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];? ? alertView = [[UIAlertView alloc] initWithTitle:@"Text" message:text delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];? ? [alertView show];? ? [alertView release];? ? return YES;}This code alerts the user with the text that was sent by the Sender app when the application is opened with a URL. Generally, you should use this data to follow up with an appropriate action within your app. Notice that we used the hostname of the URL to get our text. We did this because the URL scheme we registered functions like any other URL “scheme://hostname/path/file.php?variable=x#section" (Recall that our URL was “readtext://text"). We also URL decoded the text using the stringByReplacingPercentEscapesUsingEncoding: method as previously we had URL encoded it.Step 7: Testing the ApplicationThe time has finally come to test these two applications. They must both be built and installed to a physical iOS device. Make sure you have disconnected the device from the computer when testing and you have closed the Receiver app after disconnecting to prevent any problems. Open up the Sender app, write up some text, and hit send. The receiver app should open prompting you with the text you typed.Final ResultAdvertisementConclusionIf successful, you should now be able to easily implement inter-app communications using URL schemes. If you have any questions or comments, feel free to leave them in the comments section below. Thanks for reading!Additional Information and ResourcesPros:Does not force the user to be connected to a network, or require additional resources for web server handling.A simple, fast, and easy method of implementing communication.Provide a public communication interface that ANY app can take advantage of.Open your application from your website using an anchor tag. Ex:Open Our iPhone ApplicationCons:Unlike other platforms such as Android, iPhone does not create a stack of actions (back stacking on Android). What this means is that if you do decide to launch another application, your application will not resume when the user exits from the application you opened.When not to use URL Schemes:Sending user-sensitive data such as username and password combinations. You should never do this; instead refer to the Keychain API.Avoid using URL Schemes when you can implement the other applications functionality internally and directly, to avoid having your application close. For example, should you use a URL scheme to launch the Maps application when you could implement Maps in-app? Depending on the situation, you may have to but in many cases opening Maps in-app is sufficient.No authentication that the data you have sent will reach the correct application or whether it has reached at all, namely why sensitive data should not be sent.Resources:Apple Developer Reference (provides information on URL Schemes, and how to launch Apple apps using them)2eb5e231c8f559e595bfc3783a7e15e2?s=200&d=https%3a%2f%2fassets.tutsplus.com%2fimages%2fhub%2favatar defaultAjay PatelI am passionate about web and mobile development. I love playing around with the latest technologies in our industry. I works mostly in PHP and CMS like WordPress, Joomla. I am Founder and Content writer of? WebDesignerGeek . Now working as Web & Mobile App Developer. You can follow him on @twitter and @facebookFree trial of 780 Envato Tuts+ coursesFree trial highlightStart your free 10 day trialAdvertisementDownload AttachmentAdvertisementTranslationsEnvato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this postPowered byNative logo


http://code.tutsplus.com/tutorials/ios-sdk-working-with-url-schemes--mobile-6629

https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/Introduction/Introduction.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子逊躁,更是在濱河造成了極大的恐慌屹徘,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,729評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件沐旨,死亡現(xiàn)場(chǎng)離奇詭異森逮,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)磁携,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門褒侧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人谊迄,你說(shuō)我怎么就攤上這事闷供。” “怎么了统诺?”我有些...
    開封第一講書人閱讀 169,461評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵歪脏,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我粮呢,道長(zhǎng)婿失,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,135評(píng)論 1 300
  • 正文 為了忘掉前任啄寡,我火速辦了婚禮豪硅,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘挺物。我一直安慰自己懒浮,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,130評(píng)論 6 398
  • 文/花漫 我一把揭開白布识藤。 她就那樣靜靜地躺著砚著,像睡著了一般眯牧。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上赖草,一...
    開封第一講書人閱讀 52,736評(píng)論 1 312
  • 那天学少,我揣著相機(jī)與錄音,去河邊找鬼秧骑。 笑死版确,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的乎折。 我是一名探鬼主播绒疗,決...
    沈念sama閱讀 41,179評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼骂澄!你這毒婦竟也來(lái)了吓蘑?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,124評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤坟冲,失蹤者是張志新(化名)和其女友劉穎磨镶,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體健提,經(jīng)...
    沈念sama閱讀 46,657評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡琳猫,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,723評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了私痹。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片脐嫂。...
    茶點(diǎn)故事閱讀 40,872評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖紊遵,靈堂內(nèi)的尸體忽然破棺而出账千,到底是詐尸還是另有隱情,我是刑警寧澤暗膜,帶...
    沈念sama閱讀 36,533評(píng)論 5 351
  • 正文 年R本政府宣布匀奏,位于F島的核電站,受9級(jí)特大地震影響桦山,放射性物質(zhì)發(fā)生泄漏攒射。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,213評(píng)論 3 336
  • 文/蒙蒙 一恒水、第九天 我趴在偏房一處隱蔽的房頂上張望会放。 院中可真熱鬧,春花似錦钉凌、人聲如沸咧最。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,700評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)矢沿。三九已至滥搭,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間捣鲸,已是汗流浹背瑟匆。 一陣腳步聲響...
    開封第一講書人閱讀 33,819評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留栽惶,地道東北人愁溜。 一個(gè)月前我還...
    沈念sama閱讀 49,304評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像外厂,于是被迫代替她去往敵國(guó)和親冕象。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,876評(píng)論 2 361

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