前言app
應用內跳轉到 AppStore 的文章不少,通常都是用 SKStoreProductViewController 來實現的,不知道有沒有在乎一個問題:打開很慢!!怎麼忍?!ide
聲明
歡迎轉載,但請保留文章原始出處:)
博客園:http://www.cnblogs.com
農民伯伯: http://over140.cnblogs.comurl
正文spa
通常網上的文章的代碼:code
func openAppStore(url: String){ if let number = url.rangeOfString("[0-9]{9}", options: NSStringCompareOptions.RegularExpressionSearch) { let appId = url.substringWithRange(number) let productView = SKStoreProductViewController() productView.delegate = self productView.loadProductWithParameters([SKStoreProductParameterITunesItemIdentifier : appId], completionBlock: { [weak self](result: Bool, error: NSError?) -> Void in if result { self?.presentViewController(productView, animated: true, completion: nil) } else { self?.openAppUrl(url) } }) } else { openAppUrl(url) } } private func openAppUrl(url: String) { let nativeURL = url.stringByReplacingOccurrencesOfString("https:", withString: "itms-apps:") if UIApplication.sharedApplication().canOpenURL(NSURL(string:nativeURL)!) { UIApplication.sharedApplication().openURL(NSURL(string:url)!) } } func productViewControllerDidFinish(viewController: SKStoreProductViewController) { viewController.dismissViewControllerAnimated(true, completion: nil) }
實現的效果很好,就是很慢,點擊按鈕調用 openAppStore 要好久才能顯示出界面,就算加一個轉圈效果也不好。緣由是由於要去 linkmaker.itunes.apple.com 根據 identifier 查找連接,仔細看代碼咱們會發現 presentViewController 是在查找到結果才被調用,其實咱們能夠不用讓界面現出來,雖然時間是同樣的,可是用戶體驗會很好,修改後代碼以下:blog
func openAppStore(url: String){ if let number = url.rangeOfString("[0-9]{9}", options: NSStringCompareOptions.RegularExpressionSearch) { let appId = url.substringWithRange(number) let productView = SKStoreProductViewController() productView.delegate = self productView.loadProductWithParameters([SKStoreProductParameterITunesItemIdentifier : appId], completionBlock: { [weak self](result: Bool, error: NSError?) -> Void in if !result { productView.dismissViewControllerAnimated(true, completion: nil) self?.openAppUrl(url) } }) self.presentViewController(productView, animated: true, completion: nil) } else { openAppUrl(url) } } private func openAppUrl(url: String) { let nativeURL = url.stringByReplacingOccurrencesOfString("https:", withString: "itms-apps:") if UIApplication.sharedApplication().canOpenURL(NSURL(string:nativeURL)!) { UIApplication.sharedApplication().openURL(NSURL(string:url)!) } } func productViewControllerDidFinish(viewController: SKStoreProductViewController) { viewController.dismissViewControllerAnimated(true, completion: nil) }
代碼說明:ci
不等 loadProductWithParameters 返回直接 presentViewController ,解析失敗再嘗試用 openURL 的方式打開。博客
參考:string
http://stackoverflow.com/questions/17871920/odd-behavior-with-skstoreproductviewcontrollerit
結束
很早以前寫過這個功能,因爲用戶體驗很差代碼直接被 revert 掉了,今天又搜了一下找到了辦法。