tags: OC 30 day
因为工作的需求,今天跳级来写写网路请求。
NSURLConnection
我们利用这个类,帮我们发送请求。
他总共有两个类方法:
那我们发送网路请求要用哪一个呢?
Asyn 异步,因为网路请求,会比较慢。
我们选择完后,会创建一个线程。

看见的一个参数,必须放入一个网路请求。
NSURLRequest *request = [NSURLRequest requestWithURL:<#(nonnull NSURL *)#>]
于是,我们创建一个网路请求,网路请求里面也有一个参数,这个参数是什么呢? URL
于是做了一个URL
NSURL *url = [NSURL URLWithString:@"https://tw.yahoo.com"];
把URL带入网路请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
第二个参数使用主队列。
[NSOperationQueue mainQueue]
第三个参数cpmpletionHandler里面有三个参数
//reponse
//data
//connectionError
完整的网路请求编码如下:
//发送请求 NSURL *url = [NSURL URLWithString:@"https://tw.yahoo.com"]; //请求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //发送异步请求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { //reponse //data //connectionError if(!connectionError){ NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",html); }else{ NSLog(@"连接错误 %@",connectionError); } }];
执行看看
很顺利的拿到一大串资料了。