您的位置:首页 > 产品设计 > UI/UE

iOS之NSURLRequest NSMutableURLRequest 数据请求

2015-05-28 13:26 204 查看
iOS之NSURLRequest NSMutableURLRequest 数据请求

get 请求

[objc] view plaincopy
#pragma mark - GET登录
- (void)getLogon
{
// 1. URL
NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login.php?username=%@&password=%@", self.userName.text, self.userPwd.text];

NSURL *url = [NSURL URLWithString:urlStr];

// 2. Request
NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 3. Connection
// 1> 登录完成之前,不能做后续工作!
// 2> 登录进行中,可以允许用户干点别的会更好!
// 3> 让登录操作在其他线程中进行,就不会阻塞主线程的工作
// 4> 结论:登陆也是异步访问,中间需要阻塞住
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

if (connectionError == nil) {
// 网络请求结束之后执行!
// 将Data转换成字符串
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

// num = 2
NSLog(@"%@ %@", str, [NSThread currentThread]);

// 更新界面
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.logonResult.text = @"登录完成";
}];
}
}];

// num = 1
NSLog(@"come here %@", [NSThread currentThread]);

NSURLResponse *response = nil;
// 1. &response真的理解了吗?
// 2. error:为什么是NULL,而不是nil
// NULL是C语言的 = 0
// 在C语言中,如果将指针的地址指向0就不会有危险

// nil是OC的,是一个空对象发送消息不会出问题
//    [response MIMEType];
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];
}

post请求
[objc] view plaincopy
#pragma mark - POST登录
- (void)postLogon
{
// 1. URL
NSURL *url = [NSURL URLWithString:@"http://localhost/login.php"];

// 2. 请求(可以改的请求)
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// ? POST
// 默认就是GET请求
request.HTTPMethod = @"POST";
// ? 数据体
NSString *str = [NSString stringWithFormat:@"username=%@&password=%@", self.userName.text, self.userPwd.text];
// 将字符串转换成数据
request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding];

// 3. 连接,异步
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

if (connectionError == nil) {
// 网络请求结束之后执行!
// 将Data转换成字符串
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

// num = 2
NSLog(@"%@ %@", str, [NSThread currentThread]);

// 更新界面
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.logonResult.text = str;
}];
}
}];

// num = 1
NSLog(@"come here %@", [NSThread currentThread]);
}

使用NSURLConnection有两种方式: 第一种 如上, 第二种实现  NSURLConnectionDataDelegate 代理
[objc] view plaincopy
- (void)getLogon
{
// 1. URL
NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login.php?username=%@&password=%@", self.userName.text, self.myPwd];

NSLog(@"%@", self.myPwd);

NSURL *url = [NSURL URLWithString:urlStr];

// 2. Request
NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 3. 连接,已经10多岁了
// 是一个很古老的技术
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];

// 开始工作,在很多多线程技术中,start run
dispatch_async(dispatch_queue_create("demo", DISPATCH_QUEUE_CONCURRENT), ^{
[connection start];
});
}

#pragma mark - NSURLConnectionDataDelegate代理方法
#pragma mark 接受到响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// 准备工作
// 按钮点击就会有网络请求,为了避免重复开辟空间
if (!self.data) {
self.data = [NSMutableData data];
} else {
[self.data setData:nil];
}
}

#pragma mark 接收到数据,如果数据量大,例如视频,会被多次调用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 拼接数据,二进制流的体现位置
[self.data appendData:data];
}

#pragma mark 接收完成,做最终的处理工作
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 最终处理
NSString *str = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];

NSLog(@"%@ %@", str, [NSThread currentThread]);
}

#pragma mark 出错处理,网络的出错可能性非常高
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%@", error.localizedDescription);
}


注: 更新UI都要在主线程更新,原因要保证线程安全
[objc] view plaincopy
// 更新界面
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.logonResult.text = str;
}];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: