判断iOS应用是否开放HTTP权限的方法
从iOS9起,新特性要求App访问网络请求,要采用HTTPS协议。但是能不能判断开发者是否允许HTTP的请求,这样就不会在发起请求时候失败同时弹出以下信息:
AppTransportSecurityhasblockedacleartextHTTP(http://)resourceloadsinceitisinsecure.Temporaryexceptionscanbeconfiguredviayourapp'sInfo.plistfile.
这个需求其实是最近在弄HTTPDNS相关的一些东西,只能通过HTTP接口请求,但是希望能判断应用是否允许了HTTP的访问,如果允许才开启HTTPDNS相关的功能。
解决方法比较简单,其实就是读取info.plist看看NSAppTransportSecurity是否为YES。
Objective-C实现
-(BOOL)isHTTPEnable{
if([[[UIDevicecurrentDevice]systemVersion]compare:@"9.0"options:NSNumericSearch]!=NSOrderedAscending){
NSDictionary*infoDict=[[NSBundlemainBundle]infoDictionary];
return[[[infoDictobjectForKey:@"NSAppTransportSecurity"]objectForKey:@"NSAllowsArbitraryLoads"]boolValue];
}
returnYES;
}
使用方法:
if([selfisHTTPEnable]){
NSLog(@"HTTPenable");
}else{
NSLog(@"HTTPdisable");
}
Swift实现
funcisHTTPEnable()->Bool{
letflag=UIDevice.currentDevice().systemVersion.compare("9.0.0",options:NSStringCompareOptions.NumericSearch)
if(flag!=.OrderedAscending){
guardletinfoDict=NSBundle.mainBundle().infoDictionaryelse{
returnfalse
}
guardletappTransportSecurity=infoDict["NSAppTransportSecurity"]else{
returnfalse
}
guardletallowsArbitraryLoads=appTransportSecurity["NSAllowsArbitraryLoads"]else{
returnfalse
}
guardletres=allowsArbitraryLoadselse{
returnfalse
}
returnresas!Bool
}
returntrue
}
使用方法:
ifself.isHTTPEnable(){
print("HTTPenable")
}else{
print("HTTPdisable")
}
原文链接:http://blog.yourtion.com/is-ios-app-enable-http.html