• 使用Block,线程封装网络请求


    1.MyDownloader.h

    1 #import <Foundation/Foundation.h>
    2 
    3 @interface MyDownloader : NSObject
    4 
    5 -(void)downloadWithUrlString:(NSString *)urlString finsh:(void (^)(NSData *))finishBlock fail:(void (^)(NSError *))failBlock;
    6 //void (^finishBlock)(NSData *);
    7 
    8 @end
    View Code

    2.对应的MyDownloader.m

     1 #import "MyDownloader.h"
     2 
     3 @interface MyDownloader()<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
     4 
     5 @end
     6 
     7 @implementation MyDownloader
     8 {
     9     //下载的数据
    10     NSMutableData *_receiveData;
    11     //下载
    12     NSURLConnection *_conn;
    13     
    14     //下载结束调用的代码块
    15     void (^_finishBlock)(NSData *);
    16     void (^_failBlock)(NSError *);
    17 }
    18 
    19 -(instancetype)init
    20 {
    21     self = [super init];
    22     if (self) {
    23         _receiveData = [NSMutableData data];
    24     }
    25     return self;
    26 }
    27 
    28 -(void)downloadWithUrlString:(NSString *)urlString finsh:(void (^)(NSData *))finishBlock fail:(void (^)(NSError *))failBlock
    29 {
    30     if (_finishBlock != finishBlock) {
    31         _finishBlock = nil;
    32         _finishBlock = finishBlock;
    33     }
    34     
    35     if (_failBlock != failBlock) {
    36         _failBlock = nil;
    37         _failBlock = failBlock;
    38     }
    39     
    40     NSURL *url = [NSURL URLWithString:urlString];
    41     NSURLRequest *request = [NSURLRequest requestWithURL:url];
    42     
    43     _conn = [NSURLConnection connectionWithRequest:request delegate:self];
    44 }
    45 
    46 #pragma mark  ---NSURLConnectionDelegate----
    47 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    48 {
    49     [_receiveData setLength:0];
    50 }
    51 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    52 {
    53     [_receiveData appendData:data];
    54 }
    55 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
    56 {
    57     _finishBlock(_receiveData);
    58 }
    59 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    60 {
    61     _failBlock(error);
    62 }
    63 
    64 @end
    View Code
  • 相关阅读:
    小程序官方请求封装
    小程序天/小时/分秒倒计时封装
    小程序不定数量左右滑动中间放大轮播图效果
    小程序换行符检测换行
    小程序点击图片重新排序写法
    基于webuploader.js的单图片上传封装
    VMware Fusion 11 序列号
    Ionic 4 beta + Capacitor beta 尝鲜
    C语言学习笔记之动态分配数组空间
    C语言学习笔记之获取文件长度
  • 原文地址:https://www.cnblogs.com/liaods/p/4788915.html
Copyright © 2020-2023  润新知