#import "ASIHTTPRequest.h"
#import "ViewController.h"
#import "ASIFormDataRequest.h"
@interface ViewController ()<ASIHTTPRequestDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 创建请求
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://localhost/login.php"]];
// 传参数 username=zhangsan&password=zhang ==> NSData
[request setPostValue:@"zhangsan" forKey:@"username"];
[request setPostValue:@"zhang" forKey:@"password"];
// 代理,block,指定方法 (只需要选一个就够了吧)
[request setStartedBlock:^{
NSLog(@"block 开始请求");
}];
__weak typeof(request) weakRequest = request;
[request setCompletionBlock:^{
NSLog(@"block接收到数据%@",weakRequest.responseData);
}];
[request setDidFinishSelector:@selector(success:)];
// 设置代理
request.delegate = self;
// 开始异步
[request startAsynchronous];
}
- (void)success:(ASIFormDataRequest *)request {
NSLog(@"success %@",request.responseData);
}
// 发送异步请求
- (void)asiAsync {
NSURL *url = [NSURL URLWithString:@"http://localhost/demo.json"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
request.delegate = self;
// 发送异步请求
[request startAsynchronous];
}
#pragma mark - ASIHTTPRequest 代理
- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data {
NSLog(@"接收到数据 %@",[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]);
}
- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders {
NSLog(@"接收到响应头 %@",responseHeaders);
}
- (void)requestStarted:(ASIHTTPRequest *)request {
NSLog(@"开始请求");
}
- (void)requestFinished:(ASIHTTPRequest *)request {
NSLog(@"请求完成");
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSLog(@"请求失败");
}
- (void)asiSync:(NSURL *)url {
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSLog(@"%@",[[NSString alloc]initWithData:request.responseData encoding:NSUTF8StringEncoding]);
}
@end
网络:ASI 框架使用(同步与异步)
最新推荐文章于 2016-11-11 13:24:00 发布