Could you guys help me to translate the following code into Swift?
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@\"itms://itunes.apple.com
Swift 3 Syntax and improved with an 'if let'
if let url = URL(string: "itms-apps://itunes.apple.com/app/id1024941703"),
UIApplication.shared.canOpenURL(url){
UIApplication.shared.openURL(url)
}
UPDATE 7/5/17 (Thank you Oscar for pointing this out):
if let url = URL(string: "itms-apps://itunes.apple.com/app/id1024941703"),
UIApplication.shared.canOpenURL(url)
{
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
For me didn't worked one of this answers. (Swift 4) The app always opened the iTunes Store not the AppStore.
I had to change the url to "http://appstore.com/%Appname%" as described at this apple Q&A: https://developer.apple.com/library/archive/qa/qa1633/_index.html
for example like this
private let APPSTORE_URL = "https://appstore.com/keynote"
UIApplication.shared.openURL(URL(string: self.APPSTORE_URL)!)
(remove spaces from the app-name)
For Swift 5 (tested code) to open App Store link
if let url = URL(string: "https://itunes.apple.com/in/app/your-appName/id123456?mt=8")
{
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
else {
if UIApplication.shared.canOpenURL(url as URL) {
UIApplication.shared.openURL(url as URL)
}
}
}
For the new AppStore, simply open your app's link on AppStore and replace the https
scheme to itms-apps
scheme.
Example on Swift 4:
if let url = URL(string: "itms-apps://itunes.apple.com/us/app/my-app/id12345678?ls=1&mt=8") {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
You can find your app's link on the App Information page.
Swift 5.0:
import StoreKit
extension YourViewController: SKStoreProductViewControllerDelegate {
func openStoreProductWithiTunesItemIdentifier(_ identifier: String) {
let storeViewController = SKStoreProductViewController()
storeViewController.delegate = self
let parameters = [ SKStoreProductParameterITunesItemIdentifier : identifier]
storeViewController.loadProduct(withParameters: parameters) { [weak self] (loaded, error) -> Void in
if loaded {
self?.present(storeViewController, animated: true, completion: nil)
}
}
}
private func productViewControllerDidFinish(viewController: SKStoreProductViewController) {
viewController.dismiss(animated: true, completion: nil)
}
}
// How to use
openStoreProductWithiTunesItemIdentifier("12345")
Swift 4 with completion handler:
Make sure to update your id in the appStoreUrlPath
func openAppStore() {
if let url = URL(string: "itms-apps://itunes.apple.com/app/id..."),
UIApplication.shared.canOpenURL(url){
UIApplication.shared.open(url, options: [:]) { (opened) in
if(opened){
print("App Store Opened")
}
}
} else {
print("Can't Open URL on Simulator")
}
}