zoukankan      html  css  js  c++  java
  • 使用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
  • 相关阅读:
    [转载]memcached完全剖析--1. memcached的基础
    I/O多路复用
    How to install the zsh shell in Linux && how to set it as a default login shell
    深入理解计算机中的 csapp.h和csapp.c
    (一)网络编程基础之套接字入门
    crx
    t
    武汉第一例肺炎病例
    C语言 ## __VA_ARGS__ 宏
    NLP之中文分词cppjieba
  • 原文地址:https://www.cnblogs.com/liaods/p/4788915.html
Copyright © 2011-2022 走看看