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];
        }
        
       
     
  • 相关阅读:
    【翻译/介绍】jump consistent hash:零内存消耗,均匀,快速,简洁,来自Google的一致性哈希算法 [2015-03-13]
    现代密码学实践指南[2015年]
    本博客迁走了
    高性能web系统的架构和系统优化
    vs 2013调试的时候重启的解决方案
    年会与项目管理
    javascript 关闭窗口,弹出新窗口并带有确认关闭对话框解决办法
    成长
    POCO exception
    通过OpenGL ES在iOS平台实践增强现实(二)
  • 原文地址:https://www.cnblogs.com/zhongxuan/p/4863053.html
Copyright © 2011-2022 走看看