网络请求

网络请求

  • 网络监测

    1.根据主机名判断网络是否连接

    2.注册网络监听通知

    3.开启监听

网络监测代码

	#import "ViewController.h"
	#import "Reachability.h"
	
	@interface ViewController ()
	
	@property (nonatomic, strong) Reachability * reach;
	
	@end
	
	@implementation ViewController
	
	- (void)viewDidLoad {
	   [super viewDidLoad];
	   // Do any additional setup after loading the view, typically from a nib.
	   
	   //根据主机名判断网络是否连接
	   self.reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
	   
	   //注册网络监听通知
	   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged) name:kReachabilityChangedNotification object:nil];
	   
	   //开启监听
	   [self.reach startNotifier];
	}
	
	- (void)reachabilityChanged {
	   
	   switch (self.reach.currentReachabilityStatus) {
	       case NotReachable:
	           NSLog(@"没有网络");
	           break;
	       case ReachableViaWiFi:
	           NSLog(@"WiFi网络");
	           break;
	       case ReachableViaWWAN:
	           NSLog(@"移动蜂窝网");
	           break;
	       default:
	           NSLog(@"未知网络");
	           break;
	   }
	}
	
	- (void)dealloc {
	   
	   //把当前的对象所有通知删除
	   [[NSNotificationCenter defaultCenter] removeObserver:self];
	
	   //停止监听
	   [self.reach stopNotifier];
	}
	
	- (void)didReceiveMemoryWarning {
	   [super didReceiveMemoryWarning];
	   // Dispose of any resources that can be recreated.
  }

@end

网络请求

  • 1.建URL,访问网络资源的唯一地址

  • 2.创建网络请求

  • 3.建立连接

代码

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   // Do any additional setup after loading the view, typically from a nib.
   
   
   //1、创建URL,访问网络资源的唯一地址
   
   NSURL * url = [NSURL URLWithString:@"http://192.168.1.123/demo.json"];
   
   //2、创建网络请求
   
   /*
    cachePolicy 缓存策略
    
    NSURLRequestUseProtocolCachePolicy = 0, //自动缓存策略
    
    NSURLRequestReloadIgnoringLocalCacheData = 1, //每次都请求网络,无论本地是否存在缓存
    
    NSURLRequestReturnCacheDataElseLoad = 2,//如果有缓存返回缓存,没有就加载网络
    NSURLRequestReturnCacheDataDontLoad = 3,//如果有缓存返回缓存,没有也不加载网络
    
    timeoutInterval 请求超时 默认超时时间是60 一般设置 10 - 20s
    
    */
   
   
//    NSURLRequest * request = [NSURLRequest requestWithURL:url];
   
   NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15];
   
   //3、建立连接
   
   //sendAsynchronousRequest 建立异步网络连接
   //queue  可以传主队列,或全局队列
   
   //[NSOperationQueue mainQueue]   不用调到主队列直接更新
   
   //[[NSOperationQueue alloc] init]  则需要调回主线程更新UI
   
   [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
       //response 服务器响应信息,一般下载时有用
       //data  服务器返回的数据
       //connectionError 网络请求错误
       
       //服务器与客户端是以二进制流通讯的
       
//        NSLog(@"%@",data);
//        
//        [data writeToFile:@"/Users/dahuan/Desktop/test" atomically:YES];
       
       NSLog(@"%@",[NSThread currentThread]);
       
//        if (connectionError) {
//            
//            NSLog(@"错误信息:%@",connectionError);
//            
//        } else {
//            
//            NSLog(@"响应信息:%@",response);
//            
//            NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//            
//            NSLog(@"%@",string);
//            
//            [self.webView loadHTMLString:string baseURL:nil];
//        }
//
//        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//            //更新UI
//        }];
  
       
   }];
   
   
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
   // Dispose of any resources that can be recreated.
}

@end

同步网络请求

	#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSURL * url = [NSURL URLWithString:@"http://192.168.1.123/demo.json"];
    
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    
    //同步网络请求
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    
    NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    NSString * string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"%@",string);
    
    NSLog(@"%@",response);
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
原文地址:https://www.cnblogs.com/ldnh/p/5289490.html