Open AppStore through button
Asked Answered
E

18

81

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?)

Extraterrestrial answered 17/9, 2014 at 5:30 Comment(1)
M
163

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)
}
Mikesell answered 17/9, 2014 at 7:48 Comment(7)
Does this effectively allow the user to "gift" the app to a third party? The x-gift reference?Greenwell
Ha, X-Gift was my app's name @KatherineJenkinsExtraterrestrial
is that "id" required or can I use the aped with digits only?Autoerotic
is it possible to open non store apps? like in house developed ones?Zippy
@Zippy 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.Certes
FYI, this will open the iTunes Store app and not the App Store (then it should be itms-apps://)Euraeurasia
what is mt and uo parameter for? Where can I find all parameters I can pass to the url?Unamuno
T
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)
    }
}
Troche answered 5/11, 2016 at 3:42 Comment(2)
Nice one, but openURL() is deprecated. Now we should use this one for the same behaviour UIApplication.shared.open(url, options: [:], completionHandler: nil)Theurgy
You can also now add {action=write-review} to the url string - to jump directly to rating and writing the review...Depressor
A
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 {
Ascidium answered 11/4, 2016 at 21:43 Comment(2)
plus 1 for the StoreKit. It's a better way than just opening the AppStoreExtraterrestrial
best answer for using StoreKit.Acorn
S
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")
    }
}
Sentimentality answered 7/8, 2018 at 13:0 Comment(2)
What self.track() does?Stinkweed
In this case I was calling my analytics provider to add a record that a user opened the app store. But I just removed the line since it was unrelated. Thanks for the question!Sentimentality
S
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)
                }
           }
} 
Sybaris answered 16/7, 2019 at 17:9 Comment(0)
O
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!)
}
Onesided answered 5/2, 2015 at 16:19 Comment(0)
G
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")
Guardi answered 30/5, 2020 at 5:45 Comment(2)
what is identifier string ?Mielke
@YogeshPatel Its the app ID from the app url, say below is the url then app id would be 123456789 apps.apple.com/us/app/id123456789Guardi
P
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)

}
Pyonephritis answered 23/5, 2017 at 7:8 Comment(13)
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...#44500111Measured
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) }Pyonephritis
use this url instead of Constants.API_REDIRECT_TO_ITUNES: "itunes.apple.com/in/app/your-appName/id548615579?mt=8"Pyonephritis
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 appMeasured
It will open the app store app.Pyonephritis
i tried ` 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 } }` but its open in safari pageMeasured
but in my case its open app storePyonephritis
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 } }Measured
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.Pyonephritis
Let us continue this discussion in chat.Pyonephritis
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") } } } Measured
but i put some print function to check.. but its printing only Rate now button pressed..its not going inside that method...Measured
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()Ethbun
F
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)!)
Fen answered 14/2, 2019 at 5:39 Comment(0)
A
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)
       }
   }
}
Ab answered 19/4, 2019 at 5:38 Comment(0)
H
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") 
}
Heffner answered 21/10, 2020 at 19:1 Comment(2)
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.Lucretialucretius
this will fail -SKStoreProductViewController can't be embeded; u will receive assertion crash with SwiftUIHeartless
I
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.

Incidence answered 11/2, 2019 at 9:44 Comment(0)
E
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)
    }
}
Ehrenburg answered 11/6, 2019 at 12:10 Comment(0)
S
2

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)
Scatterbrain answered 15/9, 2022 at 10:34 Comment(1)
This is the old-fashioned not-updated solution, that doesn't work :)Ratify
S
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

Sakhuja answered 5/9, 2015 at 9:4 Comment(1)
This is identical to the above answer but with a different URL.Minivet
P
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)

Piercing answered 12/9, 2018 at 22:49 Comment(0)
P
1

In recent versions (iOS 15+) of SwiftUI you could do something like this:

Link("To App Store", destination: URL(string: "itms-apps://itunes.apple.com")!)
                .buttonStyle(.borderedProminent) // <-- iOS 15+ only

And if you want to be sure the URL is valid:

if let url = URL(string: "itms-apps://itunes.apple.com"), 
             UIApplication.shared.canOpenURL(url) {
                    Link("To App Store", destination: url)
                }
Purr answered 30/1 at 11:37 Comment(0)
R
0

2024 era, if using old-fashioned storyboards:

Save you typing:

@IBAction func tapOpenAppStore() {
    if let u = URL(string: "itms-apps://itunes.apple.com"),
      UIApplication.shared.canOpenURL(u) {
        UIApplication.shared.open(u)
    }
}

Note, simulators have no app store. It does nothing (and does not crash or hiccup) if run on a simulator.

Ratify answered 14/2 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.