從 iOS9 起,新特性要求 App 訪問網路請求,要採用 HTTPS 協議。但是能不能判斷開發人員是否允許 HTTP 的請求,這樣就不會在發起請求時候失敗同時彈出以下資訊:
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
這個需求其實是最近在弄 HTTPDNS 相關的一些東西,只能通過 HTTP 介面請求,但是希望能判斷應用是否允許了 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")}
原文連結:http://blog.yourtion.com/is-ios-app-enable-http.html