封装网络解析方法

.h

#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>

typedef void(^DataBlock)(NSData * data);

typedef void(^ImageSolveBlock)(UIImage *image);


@interface KX_NetTools : NSObject

//封装的旧方法

+(void)solveDataWithUrl:(NSString *)StringUrl

                 Method:(NSString *)method

               HttpBody:(NSString *)StringBody

              revokeBlock:(DataBlock)block;

//新方法

+(void)sslveDataWithUrl:(NSString *)StringUrl

                 Method:(NSString *)method

               HttpBody:(NSString *)StringBody

            revokeBlock:(DataBlock)block;                                          


+ (void)SessionDownLoadWithUrl:(NSString *)stringUrl revokeBlock:(ImageSolveBlock)block;


@end


.m

#import "KX_NetTools.h"


@implementation KX_NetTools


+(void)solveDataWithUrl:(NSString *)StringUrl

                 Method:(NSString *)method

               HttpBody:(NSString *)StringBody

            revokeBlock:(DataBlock)block{

    NSURL * url = [NSURL URLWithString:StringUrl];

    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];

    //将所有的字母转化成大写

    NSString * SMethod = [method uppercaseString];

    if ([@"POST" isEqualToString:SMethod]) {

        [request setHTTPMethod:SMethod];

        NSData * bodyData = [StringBody dataUsingEncoding:NSUTF8StringEncoding];

        [request setHTTPBody:bodyData];

        

    }else if ([@"GET" isEqualToString:SMethod]){

        

    }else{

        @throw [NSException exceptionWithName:@"KX Param Error" reason:@"方法类型参数错误" userInfo:nil];

        return;

    }

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

        

        block(data);

    }];

}

+ (void)SessionDownLoadWithUrl:(NSString *)stringUrl revokeBlock:(ImageSolveBlock)block{

    //1.创建 url

    NSURL * url = [NSURL URLWithString:stringUrl];

   

    NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];

    //2.创建回话

    NSURLSession *session = [NSURLSession sharedSession];

    //3.创建任务

    NSURLSessionDownloadTask * task = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        NSData * ImageData = [NSData dataWithContentsOfURL:location];

        UIImage * image = [UIImage imageWithData:ImageData];

       //从子线程回到主线程进行界面更新

        dispatch_async(dispatch_get_main_queue(), ^{

            block(image);

        });

    }];

    //启动

    [task resume];

}












  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值