iOS网络同步请求两种方法及解决iOS9后使用HTTP协议报错

//老方法

- (void)viewDidLoad {

[superviewDidLoad];

//获取文件的访问路径

NSString*path=@"http://1.studyios.sinaapp.com/getAllClass.php";

//2、封装URL

NSURL*url=[NSURLURLWithString:path];

//3、创建请求命令

NSURLRequest*request=[NSURLRequestrequestWithURL:url];

//4、响应的对象

__autoreleasingNSURLResponse*response;

//5、错误信息

__autoreleasingNSError*error;

//6、通过同步请求的方式返回data对象

NSData*data=[NSURLConnectionsendSynchronousRequest:requestreturningResponse:&responseerror:&error];

//7、json解析

NSArray*arr=[NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableLeaveserror:&error];

NSLog(@"%@",arr);

}

下面是新方法

- (void)viewDidLoad {

[superviewDidLoad];

NSString*path=@"http://1.studyios.sinaapp.com/getAllClass.php";

NSURL*url=[NSURLURLWithString:path];

//创建请求命令

NSURLRequest*request=[NSURLRequestrequestWithURL:url];

//创建回话对象通过单例方法实现

NSURLSession*session=[NSURLSessionsharedSession];

//执行回话的任务

NSURLSessionTask*task=[sessiondataTaskWithRequest:requestcompletionHandler:^(NSData*_Nullabledata,NSURLResponse*_Nullableresponse,NSError*_Nullableerror){

//json解析

NSArray*arr=[NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableLeaveserror:&error];

NSLog(@"%@",arr);

}];

//真正的执行任务

[taskresume];

}

iOS9引入了新特性App Transport Security (ATS)。

新特性要求App内访问的网络必须使用HTTPS协议。

但是要使用HTTP协议用以下解决办法:

找到Info.plist文件并在其中添加App Transport Security Settings类型Dictionary。

在App Transport Security Settings下添加Allow Arbitrary Loads类型,Boolean值设为YES



最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容