Creating a mobile app always requires opening other apps because we can’t handle it.
Of course, I’m sure most of us at the beginning thought that: my application will do everything. Later on, you find it’s hard to send an email without a mobile app, and create a whole app only to do this one small task is a huge thing. Even if you did it you could encounter a problem with calling because you can’t make a phone call in your app.
Here opening URL comes in.
Creating URL in Swift from String always returns Optional URL, I force unwrap it but you in your app should use if let or guard let.
To open some websites using HTTP or HTTPS just put create this type of link.
let defaultWebsiteURL = URL(string: “https://smashswift.com”)!
Next check if you can open this link.
if UIApplication.shared.canOpenURL(defaultWebsiteURL) {
// you can open URL
}
You shouldn’t receive here false because there is always Safari but in the case with emails, you can delete email client and you can’t open it.
The last step is to open.
UIApplication.shared.open(defaultWebsiteURL, options: [:]) { success in
print(success)
}
The first parameter is URL you want to open, the second are the options, the only one option, for now, is .universalLinksOnly, and to work with it you need to have Apple Developer Account, the last is asynchronous response indicated if the opening was successful or not.
And that’s it to open URL. In most other examples the difference will be in URL.
Let’s say you want to open URL in another browser, Chrome, the URL looks like.
let chromeWebsiteURL = URL(string: “googlechrome://smashswift.com”)!
The first time when the user will need to agree to open it.
To make a call via phone or facetime, replace 111111111 with a valid number.
let facetimeURL = URL(string: “facetime://111111111”)!
let telURL = URL(string: “tel://111111111”)!
To open the default mail app.
let defaultMailURL = URL(string: “mailto:kornel@smashswift.com”)!
To open another mail app. Here you need one more change. To open Gmail app you need to app to Info.plist file one entry
<key>LSApplicationQueriesSchemes</key>
<array>
<string>googlegmail</string>
</array>
To be able to open Outlook add the second element: ms-outlook
Now you can open Gmail app with URL
let gmailURL = URL(string: “googlegmail://co?to=kornel@smashswift.com&subject=Hi&body=Hi”)!