iOS网络编程--NSConnection的同步连接与异步连接

时间:2024-12-15 16:35:32
 //
// ZFViewController.m
// 0628-表单验证
//
// Created by zfan on 14-6-28.
// Copyright (c) 2014年 zfan. All rights reserved.
// #import "ZFViewController.h"
#import "MBProgressHUD+MJ.h" @interface ZFViewController () @property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passWordTextField; @end @implementation ZFViewController - (void)viewDidLoad
{
[super viewDidLoad];
} - (IBAction)login:(id)sender
{
//验证账号和密码是否合法
if (self.userNameTextField.text.length == )
{
[MBProgressHUD showError:@"请输入账号"];
return;
} if (self.passWordTextField.text.length == )
{
[MBProgressHUD showError:@"请输入密码"];
return;
} //取出账号和密码
NSString *userName = self.userNameTextField.text;
NSString *password = self.passWordTextField.text; //生成URL
NSString *urlPath = [NSString stringWithFormat:@"http://192.168.1.101:8080/ZFServer/login?username=%@&pwd=%@", userName, password];
NSURL *url = [NSURL URLWithString:urlPath]; //生成连接
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; //建立连接并接收返回数据(同步执行)
// NSData *loginData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil]; //建立连接并接收返回数据(异步执行)
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSData *loginData = data;
NSLog(@"%ld", (unsigned long)loginData.length);
}]; //打印返回的数据长度
NSLog(@"%@", self.userNameTextField.text);
NSLog(@"%@", self.passWordTextField.text);
// NSLog(@"%ld", (unsigned long)loginData.length);
} @end

知识要点:

1>通过NSString类方法拼接字符串,生成完整的URL路径;

2>通过NSURLRequest的类方法,利用URL建立一个NSURLRequest连接实例;

3>通过NSConnection的类方法建立连接并接受返回数据,可通过同步方式和异步方式实现:

  3.1>同步方式

[NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];

  此方法不会新建线程,返回值为NSData,由于未新建线程,因此在该方法未完成前,线程不会继续向下运行,容易造成卡死;

  3.2>异步方式

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
  NSData *loginData = data;
  NSLog(@"%ld", (unsigned long)loginData.length);
}];

  此方法会建立一个新的线程用于接受网络端返回数据,返回值为void,当数据接受完毕后会执行block中的语句;