zoukankan      html  css  js  c++  java
  • iOS中使用block进行网络请求回调

    PS:简单的使用block进行网络请求回调,非常的方便,避免了delegate的繁琐

    HttpRequest.h

    //
    //  HttpRequest.h
    //  UseBlockCallBack
    //
    //  Created by Michael on 2/13/14.
    //  Copyright (c) 2014 EIMS. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    
    typedef void (^FinishBlock)(NSString *dataString);
    
    @interface HttpRequest : NSObject<NSURLConnectionDataDelegate>
    
    @property (strong, nonatomic) NSMutableData *resultData;
    @property (strong, nonatomic) FinishBlock finishBlock;
    
    + (void)postRequestWithURL:(NSString *)urlStr
                     paramters:(NSString *)paramters
                  finshedBlock:(FinishBlock)block;
    
    @end

    HttpRequest.m

    //
    //  HttpRequest.m
    //  UseBlockCallBack
    //
    //  Created by Michael on 2/13/14.
    //  Copyright (c) 2014 EIMS. All rights reserved.
    //
    
    #import "HttpRequest.h"
    
    @implementation HttpRequest
    
    + (void)postRequestWithURL:(NSString *)urlStr
                     paramters:(NSString *)paramters
                  finshedBlock:(FinishBlock)block
    {
        HttpRequest *httpRequest = [[HttpRequest alloc]init];
        httpRequest.finishBlock = block;
        
        NSURL *url = [NSURL URLWithString:urlStr];
        NSMutableURLRequest *requset = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        [requset setHTTPBody:[paramters dataUsingEncoding:NSUTF8StringEncoding]];
        
        NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:requset delegate:httpRequest];
        NSLog(connection ? @"连接创建成功" : @"连接创建失败");
    }
    /**
     *  接收到服务器回应的时回调
     */
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        if (!self.resultData) {
            self.resultData = [[NSMutableData alloc]init];
        } else {
            [self.resultData setLength:0];
        }
        
        if ([response respondsToSelector:@selector(allHeaderFields)]) {
            NSDictionary *dic = [httpResponse allHeaderFields];
            NSLog(@"[network]allHeaderFields:%@",[dic description]);
        }
    }
    /**
     *  接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次
     */
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        [self.resultData appendData:data];
    }
    /**
     *  数据传完之后调用此方法
     */
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        NSString *resultStr = [[NSString alloc]initWithData:self.resultData
                                                   encoding:NSUTF8StringEncoding];
        if (self.finishBlock) {
            self.finishBlock(resultStr);
        }
    }
    /**
     *  网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法
     */
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        NSLog(@"network error : %@", [error localizedDescription]);
        
        if (self.finishBlock) {
            self.finishBlock(nil);
        }
    }
    
    
    @end

    在ViewController中调用:

    [HttpRequest postRequestWithURL:@"http://www.baidu.com"
                              paramters:@""
                           finshedBlock:^(NSString *dataString) {
                               NSLog(@"finish callback block, result: %@", dataString);
    }];

    祝您愉快开心 ^_^

  • 相关阅读:
    线段树 建树 单点修改 单点/区间查询
    JAVAEE学期总结
    Spring框架教程IDEA版-----更新中
    第一章操作系统引论-------批处理、分时、实时各个操作系统特点 进程与线程的区别
    读《阿法狗围棋系统的简要分析》
    matlab启动后的默认路径
    从长辈们的故事谈起
    在成为一名老司机的路上不要狂奔
    物理学与其它科学的关系
    读《现象级带货网红的自我修养》
  • 原文地址:https://www.cnblogs.com/tianglin/p/3549046.html
Copyright © 2011-2022 走看看