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

如何判斷 iOS App 是否開放 HTTP 權限

編輯:iOS 開發綜合

從 iOS 9 開始,Apple 引入 App Transport Security(ATS)機制,要求 App 的網路請求採用 HTTPS 協定。但有時候我們希望能先判斷 App 是否允許 HTTP 請求,如此一來就不會在發送請求時失敗,同時避免彈出以下訊息:

App Transport Security has blocked a cleartext HTTP (https://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

這個需求其實來自 HTTPDNS 相關的開發:由於只能透過 HTTP 介面請求,因此希望先判斷 App 是否允許 HTTP 存取,只有允許時才啟動 HTTPDNS 相關功能。

解決方法其實很簡單:讀取 Info.plist,檢查 NSAppTransportSecurity 是否為 YES 即可。

Objective-C 實作

 - (BOOL)isHTTPEnable {
     if([[[UIDevice currentDevice] systemVersion] compare:@"9.0" options:NSNumericSearch] != NSOrderedAscending){
         NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
         return [[[infoDict objectForKey:@"NSAppTransportSecurity"] objectForKey:@"NSAllowsArbitraryLoads"] boolValue];
     }
     return YES;
 }

使用方法:

 if ([self isHTTPEnable]) {
     NSLog(@"HTTP enable");
 } else {
     NSLog(@"HTTP disable");
 }

Swift 實作

 func isHTTPEnable() -> Bool {
     let flag = UIDevice.currentDevice().systemVersion.compare("9.0.0", options: NSStringCompareOptions.NumericSearch)
     if (flag != .OrderedAscending) {
         guard let infoDict = NSBundle.mainBundle().infoDictionary else { return false }
         guard let appTransportSecurity = infoDict["NSAppTransportSecurity"] else { return false }
         guard let allowsArbitraryLoads = appTransportSecurity["NSAllowsArbitraryLoads"] else { return false }
         guard let res = allowsArbitraryLoads else { return false }
         return res as! Bool
     }
     return true
 }

使用方法:

 if self.isHTTPEnable() {
     print("HTTP enable")
 } else {
     print("HTTP disable")
 }

原文連結:https://blog.yourtion.com/is-ios-app-enable-http.html

小提醒:在 iOS 9 以下的系統並未啟用 ATS,因此方法直接回傳 YES;只有在 iOS 9 以上才需要真正去讀取 Info.plist 的設定值來判斷。

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