这是个人第一篇关于ios的博客,好激动,哈哈。
访问一个网络接口,返回j son数据,mark一下。
ViewController.m
//
// ViewController.m
// NSURLConnectionGet
//
// Created by 秦启飞 on 2016/12/9.
// Copyright © 2016年 秦启飞. All rights reserved.
//
#import "ViewController.h"
//遵从NSURLConnectionDataDelegate这个协议
@interface ViewController ()<NSURLConnectionDataDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
//按钮点击事件
- (IBAction)httpGet:(id)sender {
[dataTextview setText:@"点击了按钮"];
NSString *urlString=@"http://www.kuaidi100.com/query?type=ems&postid=11";
NSURL *url=[NSURL URLWithString:urlString];
NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
//接收数据,并不是只会被调用一次的,数据被切割,该函数被调用多次。
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// NSLog(@"DATA=%@",data);
//数据添加到backData
[backData appendData:data];
}
//返回response,包括状态码等等信息
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"didReceiveResponse函数 %@",response);
//初始化data
backData=[[NSMutableData alloc]init];
// [dataUILable setText:response];
}
//请求结束
-(void) connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *result=[[NSString alloc] initWithData:backData encoding:NSUTF8StringEncoding];
[dataTextview setText:result];
NSLog(@"序列化之前%@",result);
id obj=[NSJSONSerialization JSONObjectWithData:backData options:0 error:nil];
NSLog(@"序列化之后%@",obj);
}
//网络请求错误
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"❌错误 %@",error);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
ViewController.h
这里没什么东西,只是定义了一个变量,用于接收接口返回的数据,并且最终把数据显示到UITextField中
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController{
__weak IBOutlet UITextField *dataTextview;
@public
NSMutableData *backData;
}
@end
log打印
2016-12-09 21:43:56.502 NSURLConnectionGet[10576:1100297] didReceiveResponse函数 <NSHTTPURLResponse: 0x600000235a20> { URL: http://www.kuaidi100.com/query?type=ems&postid=11 } { status code: 200, headers {
"Cache-Control" = "no-cache";
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Type" = "text/html;charset=UTF-8";
Date = "Fri, 09 Dec 2016 13:43:56 GMT";
P3P = "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"";
Server = nginx;
"Transfer-Encoding" = Identity;
Vary = "Accept-Encoding";
} }
2016-12-09 21:43:56.504 NSURLConnectionGet[10576:1100297] 序列化之前{"message":"参数错误","nu":"","ischeck":"0","condition":"","com":"","status":"400","state":"0","data":[]}
2016-12-09 21:43:56.504 NSURLConnectionGet[10576:1100297] 序列化之后{
com = "";
condition = "";
data = (
);
ischeck = 0;
message = "\U53c2\U6570\U9519\U8bef";
nu = "";
state = 0;
status = 400;
}