ASIHTTPRequest


#pragma mark - 同步请求

- (IBAction)buttonOne:(id)sender {

    

    NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];


    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];


    [request startSynchronous]; // 方法启动同步访问


    NSError *error = [request error]; // 没有基于事件的回调方法,所以从requesterror属性获取错误信息


    if(!error) {

      NSString *response = [request responseString]; // responseString,为请求的返回NSString信息

        NSLog(@"%@", response);

    }

    

}


2016-04-23 19:44:57.588 ASI[72308:950228] <!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>All-Seeing Interactive</title>

<meta name="viewport" content="width=device-width">

<link type="text/css" href="/css/s.min.css" rel="stylesheet">

</head>

<body>


异步请求的好处是不阻塞当前线程,但相对于同步请求略为复杂,至少要添加两个回调方法来获取异步事件

@interface ViewController ()<ASIHTTPRequestDelegate>


#pragma mark - 异步请求

//异步请求的好处是不阻塞当前线程,但相对于同步请求略为复杂,至少要添加两个回调方法来获取异步事件

- (IBAction)buttonTwo:(id)sender {

    

    NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

    [request setDelegate:self];

    [request startAsynchronous]; //startAsynchronous来启动网络请求

    

}

//数据请求结束

- (void)requestFinished:(ASIHTTPRequest *)request {

    NSString *responseString = [request responseString];

    NSData *responseData = [request responseData]; 

    NSLog(@"12%@", responseString);

    NSLog(@"%@", responseData);

    

}

- (void)requestFailed:(ASIHTTPRequest *)request {

    NSError *error = [request error];

}

在这里实现了两个delegate的方法,当数据请求成功时会调用requestFinished,请求失败时(如网络问题或服务器内部错误)会调用requestFailed


你可能感兴趣的:(ios,ASI,网络加载)