• IOS 使用block完成网络请求的自定义类BlockURLConnection


    一,头文件

    #import <Foundation/Foundation.h>
    //定义下载中block类型
    typedef void(^ProcessBlock) (NSURLResponse *response,NSData *data,NSError *error);
    //定义下载完成block类型
    typedef void(^CompletionBlock) (NSURLResponse *response,NSData *data,NSError *error);


    @interface BlockURLConnection : NSURLConnection<NSURLConnectionDataDelegate>
    +(BlockURLConnection *)sendAsynchronousRequest:(NSURLRequest *)request ProcessBlock:(ProcessBlock)process CompletionBlock:(CompletionBlock)completion;


    @end

    二,实现部分
    #import "BlockURLConnection.h"
    @interface BlockURLConnection()
    @property (nonatomic,strong ) NSError *error;
    @property (nonatomic,strong ) NSMutableData *data;
    @property (nonatomic,strong ) NSURLResponse *response;
    @property (nonatomic,strong ) ProcessBlock process;
    @property (nonatomic,strong ) CompletionBlock completion;

    @end

    @implementation BlockURLConnection

    +(BlockURLConnection *)sendAsynchronousRequest:(NSURLRequest *)request ProcessBlock:(ProcessBlock)process CompletionBlock:(CompletionBlock)completion
    {
        BlockURLConnection *connection=[[BlockURLConnection alloc]initWithRequest:request delegate:self];
        connection.process=process;
        connection.completion=completion;
        return connection;
    }

    -(id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate
    {
        //指定网络链接的代理是自己
        if (self=[super initWithRequest:request delegate:self]) {
            ;
        }
        return self;
    }

    //收到链接错误信息
    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        self.error=error;
    }

    //收到网络响应信息
    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        self.response=response;
        self.data=[NSMutableData data];
    }

    //收到网络消息
    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        [self.data appendData:data];
        self.process(self.response,data,self.error);
    }

    //完成接受网络消息
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        self.completion(self.response,self.data,self.error);
    }


    @end

  • 相关阅读:
    对PostgreSQL中bufmgr.c 中 bufs_to_lap的初步理解
    bgwriter 的睡眠时间差异
    对PostgreSQL中bufmgr.c 中 num_to_scan 的初步理解
    对PostgreSQL中bufmgr.c的进一步学习
    PHP 接收长url并重定向
    Request.ServerVariables小结
    Kiss Asp Framework 0.2.0RC Releaseed
    FLV编码、转换、录制、播放方案
    ASP错误信息
    Gzip简介
  • 原文地址:https://www.cnblogs.com/huntaiji/p/3475722.html
Copyright © 2020-2023  润新知