zoukankan      html  css  js  c++  java
  • 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];
        }
        
       
     
  • 相关阅读:
    [洛谷P4725]【模板】多项式对数函数
    [洛谷P4841]城市规划
    [洛谷P4346][CERC2015]ASCII Addition
    [洛谷P3978][TJOI2015]概率论
    [洛谷P4656][CEOI2017]Palindromic Partitions
    [洛谷P4889]kls与flag
    [洛谷P3810]【模板】三维偏序(陌上花开)
    [洛谷P2613]【模板】有理数取余
    [bzoj4945][Noi2017]游戏
    [洛谷P4151][WC2011]最大XOR和路径
  • 原文地址:https://www.cnblogs.com/zhongxuan/p/4863053.html
Copyright © 2011-2022 走看看