zoukankan      html  css  js  c++  java
  • 使用NSURLConnection的网络请求与封装

    訪问网络的方式:

    1、同步请求: 会堵塞主线程

    2、异步请求: 无法取消 请求过程在多线程运行

     

    基本流程:

    1、构造NSURL实例。

    2、生成NSURLRequest请求。

    3、通过NSURLConnection发送请求。

    4、通过NSURLRespond实例和NSError实例分析结果。

    5、接受返回数据。


    使用NSURLConnection发起异步请求:

    第一种方法:

    - (void)setUrl:(NSURL *)url

    {

        //使用同异步请求网络

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];

        [request setHTTPMethod:@"GET"]; //设置请求方式

        [request setURL:url];           //设置网络请求的url

        [request setTimeoutInterval:60];//设置超出时间

        //get请求不须要设置请求体

      

        self.data = [NSMutableData data];

        [NSURLConnection connectionWithRequest:request delegate:self];

    }

    //此种方法能够通过协议方法来监听数据载入的过程

    几种经常使用的协议方法:

    #pragma mark - 

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

    {

        [self.data appendData:data];

    }


    - (void)connectionDidFinishLoading:(NSURLConnection *)connection

    {

        UIImage *image = [UIImage imageWithData:self.data];

        self.image = image;

    }


    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

    {

        NSLog(@"请求失败!!!");

    }

    另外一种方法:

    - (void)setImageWithURL:(NSURL *)url

    {

    #if 0

        //使用同步请求网络

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];

        [request setHTTPMethod:@"GET"];

        [request setURL:url];

        [request setTimeoutInterval:60];

        //get请求不须要设置请求体

        NSURLResponse *response;

        //发送同步请求

        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

        UIImage *image = [UIImage imageWithData:data];

        self.image = image;

    #endif

        

    #if 1

        //使用异步请求网络

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];

        [request setHTTPMethod:@"GET"];

        [request setURL:url];

        [request setTimeoutInterval:60];

        //get请求不须要设置请求体

    //    NSURLResponse *response;

        //发送异步请求

        NSOperationQueue *queue = [[NSOperationQueue alloc]init];

        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)

        {

            UIImage *image = [UIImage imageWithData:data];

            dispatch_async(dispatch_get_main_queue(), ^{

                    self.image = image;  //主线程载入数据

            });

        }];

        

    #endif

    }


    以下简单写一个NSURLConnection的封装代码


    首先写封装 NSMutableURLRequest 的代码 得继承它

    #import <Foundation/Foundation.h>

    typedef void(^FinshLoadBlock) (NSData *);


    @interface PXRequest : NSMutableURLRequest <NSURLConnectionDataDelegate>


    @property (nonatomic,strong)NSMutableData *data;         //载入的数据

    @property (nonatomic,strong)NSURLConnection *connection; //连接对象

    @property (nonatomic,strong)FinshLoadBlock block;        //定义一个block 数据载入完后调用


    - (void)startAsynrc; //開始请求


    - (void)cancel;      //取消请求

    @end


    #import "PXRequest.h"

    @implementation PXRequest


    //開始异步请求

    - (void)startAsynrc

    {

        self.data = [NSMutableData data];

        self.connection = [NSURLConnection connectionWithRequest:self delegate:self];

    }


    - (void)cancel

    {

        [self.connection cancel];

    }


    #pragma  mark -

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

    {

        [self.data appendData:data];

    }


    - (void)connectionDidFinishLoading:(NSURLConnection *)connection

    {

        self.block(_data);

    }

    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

    {

        NSLog(@"出错信息 = %@",error);

    }

    @end


    以下封装一段数据代码:

    比方我要通过网络去訪问一段天气接口

    #import <Foundation/Foundation.h>


    typedef void(^Completion)(id result); //返回void 參数id 名字Completion


    @interface PXDataService : NSObject


    //訪问天气接口数据

    + (void)getWetheaData:(NSDictionary *)params block:(Completion)block;


    @end


    #import "PXDataService.h"

    #import "PXRequest.h"


    #define BASE_URL @"http://www.weather.com.cn/data/sk/"

    @implementation PXDataService


    //定义获取天气的接口

    + (void)getWetheaData:(NSDictionary *)params block:(Completion)block

    {

        NSString *cityCode = [params objectForKey:@"code"];

        NSString *urlstring = [BASE_URL stringByAppendingFormat:@"%@.html",cityCode];

        

        [self startRequest:params url:urlstring block:block isGet:NO];

    }


    + (void)startRequest:(NSDictionary *)param

                     url:(NSString *)urlString

                   block:(Completion)block

                   isGet:(BOOL)get

    {

        PXRequest *request = [PXRequest requestWithURL:[NSURL URLWithString:urlString]];

        if(get)

            [request setHTTPMethod:@"GET"];

        else

            [request setTimeoutInterval:60];

        //假设是post请求则须要有请求体 一般格式是 username=zpx&password=1234

    //    [request setHTTPBody:<#(NSData *)#>]

        

        

        [request startAsynrc];  //開始请求网络

        //requestblock运行时 会运行这里面的代码 block封装一段代码

        request.block = ^(NSData *data){

            

            NSString *datastring = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

            NSLog(@"data = %@",datastring);

            id ret =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

            //json解析

            block(ret);

        };

    }

    @end


    主函数代码:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    {

        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

        // Override point for customization after application launch.

        self.window.backgroundColor = [UIColor whiteColor];

        [self.window makeKeyAndVisible];

        

        UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];

        button.frame = CGRectMake(10, 50, 20, 20);

        [button addTarget:self action:@selector(load) forControlEvents:UIControlEventTouchUpInside];

        [self.window addSubview:button];

        return YES;

    }


    - (void)load

    {

        NSDictionary *params = @{@"code":@"101010300"};

        

        [PXDataService getWetheaData:params block:^(id result) {

            NSLog(@"result = %@",result);  //打印载入完的数据

        }];

    }

    点击button打印:

    2014-07-08 23:08:20.862 WXDataServer[11527:60b] result = {

        weatherinfo =     {

            Radar = "JC_RADAR_AZ9010_JB";

            SD = "70%";

            WD = "U5317U98ce";

            WS = "0U7ea7";

            WSE = 0;

            city = "U671dU9633";

            cityid = 101010300;

            isRadar = 1;

            temp = 24;

            time = "22:55";

        };

    }


  • 相关阅读:
    ASP.NET 如何取得 Request URL 的各個部分
    正则表达式
    sql server 存储过程中拼接sql,转义单引号
    C# 过滤敏感字符
    Facebook “Invite” 弹出窗口
    Silverlight 4 动态换Theme
    silverlight 4 com组件调用
    Silverlight 4 COM+ 操作支持示例集
    如何创建silverlight离开浏览器的应用程序
    Silverlight 4 的 WCF NET.TCP 协议
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/6913069.html
Copyright © 2011-2022 走看看