判斷iOS應用是否開放HTTP許可權的方法_IOS

來源:互聯網
上載者:User

從 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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.