Eventually, I want to incorporate SKStoreProductViewController into a project I'm working on so to start I thought I'd recreate what was posted here. The only thing is, when I click on my button in the simulator (xcode 14.2) no modal is appearing. Could it be because I need to run this on a real device or maybe because storeViewController.loadProduct is 'silently failing'? Any and all help is much appreciated!
My dummy app:
//
// ViewController.swift
// SKStoreProductViewController Demo
//
import UIKit
import StoreKit
class ViewController: UIViewController {
let testFlightAppURL = URL(string: "https://apps.apple.com/us/app/testflight/id899247664")!
let testFlightProductID = 899247664
private let button: UIButton = {
let button = UIButton()
button.backgroundColor = .darkGray
button.setTitle("Open App Store", for: .normal)
return button
}()
override func viewDidLoad() {
view.addSubview(button)
button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
button.frame = CGRect(x: 30,
y: view.frame.height-150-view.safeAreaInsets.bottom,
width: view.frame.size.width-60,
height: 55)
}
@objc func didTapButton() {
openAppStore()
}
func openAppStore() {
// 2. Create an SKStoreProductViewController instance and set its delegate
let storeViewController = SKStoreProductViewController()
storeViewController.delegate = self
// 3. Indicate a specific product by passing its iTunes item identifier
let parameters = [SKStoreProductParameterITunesItemIdentifier: testFlightProductID]
storeViewController.loadProduct(withParameters: parameters) { _, error in
if error != nil {
// In case there is an issue loading the product, open the URL directly
UIApplication.shared.open(self.testFlightAppURL)
} else {
self.present(storeViewController, animated: true)
}
}
}
}
// MARK: - SKStoreProductViewControllerDelegate
// 4. A simple implementation of SKStoreProductViewController.
// Delegate dismisses the view controller when the user completes the purchase.
extension ViewController: SKStoreProductViewControllerDelegate {
func productViewControllerDidFinish(_ viewController: SKStoreProductViewController) {
viewController.dismiss(animated: true)
}
}
Testing on a real device resolved the issue for me.