78

Could you guys help me to translate the following code into Swift?

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms://itunes.apple.com/de/app/x-gift/id839686104?mt=8&uo=4"]];

(or do I have to take this link: itms://itunes.apple.com/app/id839686104?)

starball
  • 20,030
  • 7
  • 43
  • 238
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
  • 4
    [Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it.](http://stackoverflow.com/help/on-topic) I know this is not homework question, but you still need to show some effect. – Bryan Chen Sep 17 '14 at 05:39

16 Answers16

152

Here. But I highly suggest you learn the basics of Swift!

UIApplication.sharedApplication().openURL(NSURL(string: "itms://itunes.apple.com/de/app/x-gift/id839686104?mt=8&uo=4")!)

If you wanna open the AppStore in Swift 5:

if let url = URL(string: "itms-apps://itunes.apple.com/app/id1629135515") {
    UIApplication.shared.open(url)
}
Claudio Silva
  • 3,743
  • 1
  • 26
  • 27
Atomix
  • 13,427
  • 9
  • 38
  • 46
  • Does this effectively allow the user to "gift" the app to a third party? The `x-gift` reference? – Katherine Jenkins May 26 '16 at 11:46
  • 1
    Ha, X-Gift was my app's name @KatherineJenkins – LinusGeffarth Oct 17 '16 at 19:56
  • is that "id" required or can I use the aped with digits only? – Johnykutty Jan 10 '17 at 13:22
  • is it possible to open non store apps? like in house developed ones? – Adam Feb 24 '17 at 01:27
  • @Adam Yes this is possible via associated domains and deep linking. Let's say the app you're developing responds to a custom scheme mycoolapp://. This means if some other app calls openUrl on a URL with a scheme of "mycoolapp://" and your app exists on that device, the device will attempt to open that link with your app. How the link is handled is determined by your app. – FateNuller Sep 29 '17 at 18:43
  • 7
    FYI, this will open the *iTunes Store* app and not the *App Store* (then it should be `itms-apps://`) – gabuchan Dec 14 '18 at 07:28
  • what is `mt` and `uo` parameter for? Where can I find all parameters I can pass to the url? – Bartłomiej Semańczyk Jul 15 '19 at 08:35
74

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)
    }
}
Stuart Casarotto
  • 1,187
  • 9
  • 16
  • 5
    Nice one, but openURL() is deprecated. Now we should use this one for the same behaviour UIApplication.shared.open(url, options: [:], completionHandler: nil) – Oscar May 28 '17 at 09:14
  • 1
    You can also now add `{action=write-review}` to the url string - to jump directly to rating and writing the review... – Ahmed Khedr Apr 28 '18 at 11:01
20

I use this combination, its better for rate/shopping.

(partially from here)

    @IBAction func rateMe(sender: AnyObject) {
    if #available(iOS 8.0, *) {
        openStoreProductWithiTunesItemIdentifier("107698237252");
    } else {
        var url  = NSURL(string: "itms://itunes.apple.com/us/app/xxxxxxxxxxx/id107698237252?ls=1&mt=8")
        if UIApplication.sharedApplication().canOpenURL(url!) == true  {
            UIApplication.sharedApplication().openURL(url!)
        }

    }
}
func openStoreProductWithiTunesItemIdentifier(identifier: String) {
    let storeViewController = SKStoreProductViewController()
    storeViewController.delegate = self

    let parameters = [ SKStoreProductParameterITunesItemIdentifier : identifier]
    storeViewController.loadProductWithParameters(parameters) { [weak self] (loaded, error) -> Void in
        if loaded {
            // Parent class of self is UIViewContorller
            self?.presentViewController(storeViewController, animated: true, completion: nil)
        }
    }
}
func productViewControllerDidFinish(viewController: SKStoreProductViewController) {
    viewController.dismissViewControllerAnimated(true, completion: nil)
}

don't forget to import and delegate:

import StoreKit

class RateMeViewController: UIViewController, SKStoreProductViewControllerDelegate {
Community
  • 1
  • 1
djdance
  • 3,110
  • 27
  • 33
15

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")
    }
}
mobilecat
  • 1,429
  • 13
  • 11
12

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)
                }
           }
} 
Hardik Thakkar
  • 15,269
  • 2
  • 94
  • 81
11

Since other answers didn't work for me (Swift, Xcode 6.1.1) here I post my solution:

var url  = NSURL(string: "itms://itunes.apple.com/de/app/x-gift/id839686104?mt=8&uo=4")

if UIApplication.sharedApplication().canOpenURL(url!) {
    UIApplication.sharedApplication().openURL(url!)
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Andrej
  • 7,266
  • 4
  • 38
  • 57
7

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")
user1039695
  • 981
  • 11
  • 20
4

Check newer app update available on iTunes in Swift 3

let currentAppVersion = Bundle.main.infoDictionary
Alamofire.request("http://itunes.apple.com/jp/lookup/?id=548615", method: .get, parameters: nil, headers: nil).responseJSON { response in
        if let value = response.result.value as? [String: AnyObject] {
            let versionNum = value["results"]?.value(forKey: "version") as? NSArray
            if versionNum?[0] as! String != currentAppVersion?["CFBundleShortVersionString"] as! String {
                self.alertForUpdateApp()
            }
        }
    }

func alertForUpdateApp() {

    let alertController = UIAlertController(title: "Update Available", message: "There is a newer version of this app available", preferredStyle: .alert)
    let alertActionCancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    let alertActionUpdate = UIAlertAction(title: "Update", style: .default, handler: { _ in
        if let url = URL(string: Constants.API_REDIRECT_TO_ITUNES),
            UIApplication.shared.canOpenURL(url){
            UIApplication.shared.open(url, options: [:], completionHandler: nil)

        }
    })

    alertController.addAction(alertActionCancel)
    alertController.addAction(alertActionUpdate)

    let pushedViewControllers = (self.window?.rootViewController as! UINavigationController).viewControllers
    let presentedViewController = pushedViewControllers[pushedViewControllers.count - 1]

    presentedViewController.present(alertController, animated: true, completion: nil)

}
Raj Joshi
  • 2,669
  • 2
  • 30
  • 37
  • i need to open my app store of my iphone..by pressing rate me button in my app. so that i need to open my app in app store itself in my iphone...how can i do with ur code..here my post...https://stackoverflow.com/questions/44499611/trigger-app-store-to-open-in-mobile-to-open-particular-app?noredirect=1#comment75992581_44499611 – hybrid Dev Jun 12 '17 at 12:43
  • You should integrate this code: if let url = URL(string: Constants.API_REDIRECT_TO_ITUNES), UIApplication.shared.canOpenURL(url){ UIApplication.shared.open(url, options: [:], completionHandler: nil) } – Raj Joshi Jun 12 '17 at 12:51
  • 1
    use this url instead of Constants.API_REDIRECT_TO_ITUNES: "https://itunes.apple.com/in/app/your-appName/id548615579?mt=8" – Raj Joshi Jun 12 '17 at 12:55
  • but does this code will trigger the app store to open or any browser to open...because i need an app store app to open and show the app – hybrid Dev Jun 12 '17 at 13:09
  • It will open the app store app. – Raj Joshi Jun 13 '17 at 06:21
  • i tried ` if let url = URL(string: "https://itunes.apple.com/in/app/Spending Tracker/id548615579?mt=8"), UIApplication.shared.canOpenURL(url){ if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { // Fallback on earlier versions } }` but its open in safari page – hybrid Dev Jun 13 '17 at 06:23
  • but in my case its open app store – Raj Joshi Jun 13 '17 at 06:26
  • does my code correct : `if let url = URL(string: "itunes.apple.com/in/app/Spending Tracker/id548615579?mt=8"), UIApplication.shared.canOpenURL(url){ if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { // Fallback on earlier versions } }` – hybrid Dev Jun 13 '17 at 06:27
  • There is no issue in your code I think you running this in simulator. If you run app on iPhone it will open app store link. – Raj Joshi Jun 13 '17 at 06:37
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/146488/discussion-between-raj-joshi-and-hybrid-dev). – Raj Joshi Jun 13 '17 at 06:38
  • i tried this cide again `@IBAction func rateNowButtonPressed(_ sender: Any) { print("Rate now button pressed") if let url = URL(string: "https://itunes.apple.com/in/app/Spending Tracker/id548615579?mt=8"), UIApplication.shared.canOpenURL(url){ if #available(iOS 10.0, *) { print("inside function to open appa store") UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { // Fallback on earlier versions print("it's failed") } } } ` – hybrid Dev Jun 13 '17 at 07:54
  • but i put some print function to check.. but its printing only `Rate now button pressed`..its not going inside that method... – hybrid Dev Jun 13 '17 at 07:57
  • I'd like to mention that the iTunes lookup can have caching issues, meaning that it won't always return you the latest version. One way to prevent this is to clear the cache before the call: `URLCache.shared.removeAllCachedResponses()` – Janneman Jun 30 '17 at 09:07
3

If you want to open in app store use

 let appstoreUrl =  "https://itunes.apple.com/in/app/myapp-test/id11111111?mt=8"
 UIApplication.shared.openURL(URL(string: appstoreUrl)!)

if you want in itune store use

  let ituneUrl =  "itms-apps://itunes.apple.com/in/app/myapp-test/id11111111?mt=8"
 UIApplication.shared.openURL(URL(string: ituneUrl)!)
Devesh.452
  • 893
  • 9
  • 10
3

In Swift 4.2 and Xcode 10.2

You have two ways to open App Store or iTunes Store

If you want to open App Store use https or if you want to open iTunes Store use itms

Ex: https://itunes.apple.com/in/app/yourAppName/id14****4?mt=8 //For App Store

itms://itunes.apple.com/in/app/yourAppName/id14****4?mt=8 //For iTunes Store

Method 1: This is simple direct and old approach

let url  = NSURL(string: "https://itunes.apple.com/in/app/smsdaddy/id1450172544?mt=8")//itms   https
    if UIApplication.shared.canOpenURL(url! as URL) {
        UIApplication.shared.openURL(url! as URL)
    }

Method 2: New approach

if let url = URL(string: "https://itunes.apple.com/in/app/smsdaddy/id1450172544?ls=1&mt=8") {
   if #available(iOS 10.0, *) {
       UIApplication.shared.open(url, options: [:], completionHandler: nil)
   } else {
       // Earlier versions
       if UIApplication.shared.canOpenURL(url as URL) {
          UIApplication.shared.openURL(url as URL)
       }
   }
}
Naresh
  • 16,698
  • 6
  • 112
  • 113
3

SwiftUI

import StoreKit

struct StoreView: UIViewControllerRepresentable {

    let appID: String
 
     
    func makeUIViewController(context: UIViewControllerRepresentableContext<StoreView>) -> SKStoreProductViewController {
        let sKStoreProductViewController = SKStoreProductViewController()
        let parameters = [ SKStoreProductParameterITunesItemIdentifier : appID]
        sKStoreProductViewController.loadProduct(withParameters: parameters)
        return sKStoreProductViewController
    }

    func updateUIViewController(_ uiViewController: SKStoreProductViewController, context: UIViewControllerRepresentableContext<StoreView>) {

    }

}

//how to use

.sheet(isPresented: $showAppAtStore){
StoreView(appID: "12345678") 
}
nirav dinmali
  • 197
  • 11
  • if you want to do this to update your own app, however, this fails in some versions of iOS since the app cannot be updated while loaded. Pity. – Garr Godfrey Feb 04 '21 at 00:52
  • 2
    this will fail -`SKStoreProductViewController` can't be embeded; u will receive assertion crash with SwiftUI – hbk Nov 25 '21 at 17:30
3

For those looking for the updated working solution

Most of the given solutions here are outdated & deprecated, like "canOpenURL", "openURL" etc.

let appStoreLink = "https://apps.apple.com/app/{app-name}/{app-id}"

guard let url = URL(string: appStoreLink) else { return }
UIApplication.shared.open(url)
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
tanmoy
  • 1,276
  • 1
  • 10
  • 28
2

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.

meow2x
  • 2,056
  • 22
  • 27
2

Swift 5

let url = "your app url"
if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
 } 
else {
    // Earlier versions 
    if UIApplication.shared.canOpenURL(url as URL) {
        UIApplication.shared.openURL(url as URL)
    }
}
Shakeel Ahmed
  • 5,361
  • 1
  • 43
  • 34
1
    var url  = NSURL(string: "itms-apps://itunes.apple.com/app/id1024941703")
    if UIApplication.sharedApplication().canOpenURL(url!) == true  {
        UIApplication.sharedApplication().openURL(url!)
    }

Xcode 6.4

1

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)

Marco Weber
  • 829
  • 10
  • 19