Swift 跳转App Store下载页的两种方式

1、直接跳转App Store

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        //弹出Alert
        let  alertVC =  UIAlertController (title: "觉得好用的话,给我个评价吧!", message: nil, preferredStyle: .alert)
        let cancelAction =  UIAlertAction(title: "暂不评价", style: .cancel, handler: nil )
        let okAction = UIAlertAction(title: "OK", style: .default) {[weak self] (action) in
            self?.goAppStore()
        }
        alertVC.addAction(cancelAction)
        alertVC.addAction(okAction)
        self.present(alertVC, animated: true, completion: nil)
    }

///跳转App Store
private func goAppStore() {
        let str = "itms-apps://itunes.apple.com/app/id444934666"
        guard let url = URL(string: str) else { return }
        let can = UIApplication.shared.canOpenURL(url)
        if can {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [:]) { (b) in
                    print("打开结果: \(b)")
                }
            } else {
                //iOS 10 以前
                UIApplication.shared.openURL(url)
            }
        }
    }

2、App内部弹出AppStore下载界面

这种效果常见于广告点击,比如你在刷今日头条,刷着刷这就会看到一条游戏广告,点击之后就会弹出这个游戏的App Store下载页(而不是跳转到App Store里)。实现方式如下:

先导入StoreKit: import StoreKit

@IBAction func showAppStorePageClick(_ sender: Any) {
        showAppStoreVC()
    }

///在应用内弹出App Store
    private func showAppStoreVC() {
        let storeVC = SKStoreProductViewController()
        //设置代理,注意这很重要,不如弹出就没法dismiss了
        storeVC.delegate = self
        self.present(storeVC, animated: true, completion: nil)
        //加载应用数据
        let param = [SKStoreProductParameterITunesItemIdentifier: "1142110895"]
        storeVC.loadProduct(withParameters: param) { (b, error) in
            if let error = error {
                print("加载错误: \(error)")
            }
        }
    }

实现代理

extension ViewController: SKStoreProductViewControllerDelegate {
    
    func productViewControllerDidFinish(_ viewController: SKStoreProductViewController) {
        //在代理方法里dismiss这个VC
        viewController.dismiss(animated: true, completion: nil)
    }
    
}

你可能感兴趣的:(Swift 跳转App Store下载页的两种方式)