The URL scheme is an fascinating function supplied by the iOS SDK that enables builders to launch system apps and third-party apps by way of URLs. For instance, let’s say your app shows a telephone quantity, and also you wish to make a name every time a consumer faucets that quantity. You need to use a selected URL scheme to launch the built-in telephone app and dial the quantity mechanically. Equally, you need to use one other URL scheme to launch the Message app for sending an SMS. Moreover, you may create a customized URL scheme to your personal app in order that different purposes can launch your app by way of a URL. You’ll see what I imply in a minute.
As regular, we’ll construct an app to show the usage of URL schemes. We are going to reuse the QR code reader app that was constructed within the earlier chapter. When you haven’t learn the QR code tutorial, return and browse it earlier than persevering with on.
Thus far, the demo app is able to decoding a QR code and displaying the decoded message on display. On this chapter, we’ll make it even higher. When the QR code is decoded, the app will launch the corresponding app primarily based on the kind of the URL.
To begin with, first obtain the QRCodeReader app. When you compile and run the app, you’ll have a easy QR code reader app. Notice that the app solely works on an actual iOS system.
Pattern QR Codes
Right here I embody some pattern QR codes that you need to use to check the app. Alternatively, you may create your QR code utilizing on-line companies like www.qrcode-monkey.com. Open the demo app and level your system’s digicam at one of many codes. It’s best to see the decoded message.
Utilizing URL Schemes
For a lot of the built-in purposes, Apple gives help for URL schemes. As an illustration, you utilize the mailto
scheme to open the Mail app (e.g. mailto:[email protected]
) or the tel
scheme to provoke a telephone name (e.g. tel://743234028
). To open an software with a customized URL scheme, all it is advisable to do is name the open(_:choices:completionHandler:)
technique of the UIApplication
class. Right here is the road of code:
UIApplication.shared.open(url, choices: [:], completionHandler: nil) |
Now, we’ll modify the demo app to open the corresponding app when a QR code is decoded. Open the Xcode challenge and choose the QRScannerController.swift
file. Add a helper technique known as launchApp
within the class:
if let url = URL(string: decodedURL) {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, choices: [:], completionHandler: nil)
}
}
})
let cancelAction = UIAlertAction(title: “Cancel”, type: UIAlertActionStyle.cancel, handler: nil)
alertPrompt.addAction(confirmAction)
alertPrompt.addAction(cancelAction)
current(alertPrompt, animated: true, completion: nil)
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
func launchApp(decodedURL: String) { let alertPrompt = UIAlertController(title: “Open App”, message: “You are going to open (decodedURL)“, preferredStyle: .actionSheet) let confirmAction = UIAlertAction(title: “Verify”, type: UIAlertActionStyle.default, handler: { (motion) –> Void in
if let url = URL(string: decodedURL) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, choices: [:], completionHandler: nil) } } })
let cancelAction = UIAlertAction(title: “Cancel”, type: UIAlertActionStyle.cancel, handler: nil)
alertPrompt.addAction(confirmAction) alertPrompt.addAction(cancelAction)
current(alertPrompt, animated: true, completion: nil) } |
The launchApp
technique takes in a URL decoded from the QR code and creates an alert immediate. If the consumer faucets the Verify button, the app then creates an URL
object and opens it accordingly. iOS will then open the corresponding app primarily based on the given URL.
Within the metadataOutput
technique, which is named when a QR code is detected, insert a line of code to name the launchApp
technique:
launchApp(decodedURL: metadataObj.stringValue!) |
Place the above line of code proper after:
messageLabel.textual content = metadataObj.stringValue |
Now compile and run the app. Level your system’s digicam at one of many pattern QR codes (e.g. tel://743234028
). The app will immediate you with an motion sheet when the QR code is decoded. When you faucet the Verify button, it opens the Cellphone app and initiates the decision.
However there’s a minor difficulty with the present app. When you look into the console, you must discover the next warning:
2017–12–12 12:52:05.343934+0800 QRCodeReader[33092:8714123] Warning: Try to current <UIAlertController: 0x10282dc00> on <QRCodeReader.QRScannerController: 0x107213aa0> whereas a presentation is in progress!
|
The launchApp
technique is named each time when a barcode or QR code is scanned. So the app could current one other UIAlertController
when there may be already a UIAlertController
introduced. To resolve the problem, we’ve to verify if the app has introduced a UIAlertController
object earlier than calling the current(_:animated:completion:)
technique.
In iOS, if you current a view controller modally utilizing the current(_:animated:completion:)
technique, the introduced view controller is saved within the presentedViewController
property of the present view controller. For instance, when the QRScannerController
object calls the current(_:animated:completion:)
technique to current the UIAlertController
object, the presentedViewController
property is about to the UIAlertController
object. When the UIAlertController
object is dismissed, the presentedViewController
property will probably be set to nil
.
With this property, it’s fairly straightforward for us to repair the warning difficulty. All it is advisable to do is to place the next code firstly of the launchApp
technique:
if presentedViewController != nil { return } |
We merely verify if the property is about to a selected view controller, and current the UIAlertController
object provided that there isn’t any introduced view controller. Now run the app once more. The warning ought to go away.
One factor you could discover is that the app can not open these two URLs:
fb://feed
whatsapp://ship?textual content=Good day!
These URLs are often called customized URL schemes created by third-party apps. For iOS 9 and later, the app is just not in a position to open these customized URLs. Apple has made a small change to the dealing with of URL scheme, particularly for the canOpenURL()
technique. If the URL scheme is just not registered within the whitelist, the tactic returns false
. When you confer with the console messages, you must see the error like this:
2017–12–12 12:58:26.771183+0800 QRCodeReader[33113:8719488] –canOpenURL: failed for URL: “fb://feed” – error: “This app is just not allowed to question for scheme fb” |
This explains why the app can not open Fb and Whatsapp even it will possibly decode their URLs. We are going to focus on extra about customized URL scheme within the subsequent part and present you how one can workaround this difficulty.
Creating Your Customized URL Scheme
Within the pattern QR codes, I included two QR codes from third get together apps:
- Fb –
fb://feed
- Whatsapp –
whatsapp://ship?textual content=Good day!
The primary URL is used to open the information feed of the consumer’s Fb app. The opposite URL is for sending a textual content message utilizing Whatsapp. Curiously, Apple permits builders to create their very own URLs for speaking between apps. Let’s see how we are able to add a customized URL to our QR Reader app.
We’re going to create one other app known as TextReader. This app serves as a receiver app that defines a customized URL and accepts a textual content message from different apps. The customized URL will appear to be this:
When an app (e.g. QR Code Reader) launches the URL, iOS will open the TextReader app and move it the Good day! message. In Xcode, create a brand new challenge utilizing the Single View Utility template and title it TextReader
. As soon as the challenge is created, develop the Supporting Information folder within the challenge navigator and choose Information.plist
. Proper click on any clean areaU and choose Add Row
to create a brand new key.
You’ll be prompted to pick a key from a drop-down menu. Scroll to the underside and choose URL sorts
. This creates an array merchandise. You possibly can additional click on the disclosure icon (i.e. triangle) to develop it. Subsequent, choose Merchandise 0
. Click on the disclosure icon subsequent to the merchandise and develop it to indicate the URL identifier line. Double-click the worth subject to fill in your identifier. Usually, you set the worth to be the identical because the bundle ID (e.g. com.appcoda.TextReader).
Subsequent, proper click on on Merchandise 0
and choose Add Row
from the context menu. Within the dropdown menu, choose URL Schemes
so as to add the merchandise.
Once more, click on the disclosure icon of URL Schemes to develop the merchandise. Double click on the worth field of Merchandise 0
and key in textreader
. When you’ve adopted the procedures accurately, your URL sorts settings ought to appear to be this:
That’s it. We have now configured a customized URL scheme within the TextReader app. Now the app accepts the URL within the type of textreader://<message>
. We nonetheless want to put in writing a number of traces of code such that it is aware of what to do when one other app launches the customized URL (e.g. textreader://Good day!
).
As you understand, the AppDelegate
class implements the UIApplicationDelegate
protocol. The strategy outlined within the protocol provides you an opportunity to work together with necessary occasions through the lifetime of your app.
If there’s a Open a URL occasion despatched to your app, the system calls the software(_:open:choices:)
technique of the app delegate. Due to this fact, you’ll have to implement the tactic as a way to reply to the launch of the customized URL.
elective func software(_ app: UIApplication, open url: URL, choices: [UIApplicationOpenURLOptionsKey : Any] = [:]) –> Bool
|
Open AppDelegate.swift
and insert the next code to implement the tactic:
let message = url.host?.removingPercentEncoding
let alertController = UIAlertController(title: “Incoming Message”, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: “OK”, type: UIAlertActionStyle.default, handler: nil)
alertController.addAction(okAction)
window?.rootViewController?.current(alertController, animated: true, completion: nil)
return true
}
func software(_ app: UIApplication, open url: URL, choices: [UIApplicationOpenURLOptionsKey : Any] = [:]) –> Bool {
let message = url.host?.removingPercentEncoding let alertController = UIAlertController(title: “Incoming Message”, message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: “OK”, type: UIAlertActionStyle.default, handler: nil) alertController.addAction(okAction)
window?.rootViewController?.current(alertController, animated: true, completion: nil)
return true } |
From the arguments of the software(_:open:choices:)
technique, you will get the URL useful resource to open. As an illustration, if one other app launches textreader://Good day!
, then the URL will probably be embedded within the URL object. The primary line of code extracts the message by utilizing the host
property of the URL
construction.
URLs can solely include ASCII characters, areas are usually not allowed. For characters exterior the ASCII character set, they need to be encoded utilizing URL encoding. URL encoding replaces unsafe ASCII characters with a % adopted by two hexadecimal digits and an area with %20
. For instance, “Good day World!” is encoded to Hellopercent20World! The removingPercentEncoding
technique is used to decode the message by eradicating the URL % encoding. The remainder of the code could be very easy. We instantiate a UIAlertController
and current the message on display.
When you compile and run the app, you must see a clean display. That’s regular as a result of the TextReader app is triggered by one other app utilizing the customized URL. You may have two methods to check the app. You possibly can open cell Safari and enter textreader://Nice!%20Itpercent20works!
within the deal with bar – you’ll be prompted to open the TextReader app. As soon as confirmed, the system ought to redirect you to the TextReader app and shows the Nice! It really works!
message.
Alternatively, you need to use the QR Code Reader app for testing. When you open the app and level the digicam to the QR code proven under, the app ought to be capable to decode the message however fails to open the TextReader app.
The console ought to present you the next error:
2017–12–12 13:28:52.795789+0800 QRCodeReader[33176:8736098] –canOpenURL: failed for URL: “textreader://Nice!%20Itpercent20works!” – error: “This app is just not allowed to question for scheme textreader”
|
As defined earlier, Apple has made some adjustments to the canOpenURL
technique since iOS 9. It’s important to register the customized URL schemes earlier than the tactic returns true
. To register a customized scheme, open Information.plist
of the QRReaderDemo challenge and add a brand new key named LSApplicationQueriesSchemes
. Set the sort to Array
and add the next gadgets:
When you’ve made the change, take a look at the QR Reader app once more. Level to a QR code with a customized URL scheme (e.g. textreader). The app ought to be capable to launch the corresponding app.
Moreover, for those who scan the QR code of the Fb scheme or Whatsapp scheme, the app ought to now be capable to launch the Fb/Whatsapp app accordingly.