IOS 异步GET方法请求

1.添加协议NSURLConnectionDelegate

2.引入头文件“NSString+URLEncoding”,用来处理URL进行编码。

3.引入头文件“NSNumber+Message”,用来处理把服务器返回消息代码转为用户能看懂的消息。

4.声明NSMutableData类型的datas,用来存放从服务器返回的数据

5.声明NSMutableArray类型的listData,用来保存数据列表

6.声明DetailViewController控制器类型的detailViewController

7.函数- (void)startRequest,开始请求Web Service

-(void)startRequest
{    
    
    NSString *strURL = [[NSString alloc] initWithFormat:
                        @"http://iosbook3.com/service/mynotes/webservice.php?email=%@&type=%@&action=%@",
                        @"<你的iosbook3.com用户邮箱>",@"JSON",@"query"];
    
    NSURL *url = [NSURL URLWithString:[strURL URLEncodedString]];
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    
    NSURLConnection *connection = [[NSURLConnection alloc]
                                   initWithRequest:request
                                   delegate:self];
    
    if (connection) {
        _datas = [NSMutableData new];
    }
    
}

 

8.NSURLConnection回调方法

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_datas appendData:data];//不断的接收服务器端返回的数据
}


-(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error {
    
    NSLog(@"%@",[error localizedDescription]);
}

//如果加载成功就回调
- (void) connectionDidFinishLoading: (NSURLConnection*) connection {
    NSLog(@"请求完成...");
    NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:_datas options:NSJSONReadingAllowFragments error:nil];
    [self reloadView:dict];
}

 

 

9.重新加载表视图

-(void)reloadView:(NSDictionary*)res
{
    NSNumber *resultCodeObj = [res objectForKey:@"ResultCode"];
    if ([resultCodeObj integerValue] >=0)
    {
        self.listData = [res objectForKey:@"Record"];
        [self.tableView reloadData];
    } else {
        NSString *errorStr = [resultCodeObj errorMessage];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误信息"
                                                            message:errorStr
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles: nil];
        [alertView show];
    }
    
   

 

 

 

你可能感兴趣的:(IOS 异步GET方法请求)