您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

應用內打開 App Store 詳情頁:把「很慢」的問題修掉

編輯:iOS 開發綜合

前言

在應用內跳轉 App Store 的文章很多,基本都是用 SKStoreProductViewController 實作。但很少有人提到一個真實存在的問題:打開特別慢。點下去之後要等上好一會兒,界面才浮上來,即便加個轉圈動畫也救不回來。

一般寫法

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

慢在哪裡

關鍵在 loadProductWithParameters 需要去 linkmaker.itunes.apple.com 依 identifier 查回真正的連結,這趟網路往返是省不掉的。仔細看上面的代碼:presentViewController 被寫在 completionBlock 內部,也就是說一定要等查詢結果回來,界面才開始顯示。等待時間沒變,但使用者感受到的是「按了沒反應」。

改法:先讓界面出來

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

代碼說明

不等 loadProductWithParameters 返回,直接 presentViewController;查詢失敗時再 dismiss 並回退到 openURL 方案。總耗時一模一樣,但使用者的感知完全不同——這正是「反饋要快於結果」的經典體驗優化。

參考

https://stackoverflow.com/questions/17871920/odd-behavior-with-skstoreproductviewcontroller

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved