UI11_网络封装(17-08-17)

//
//  ViewController.m
//  UI11_网络封装
//
//  Created by lanou3g on 17/8/17.
//  Copyright © 2017年 lanou3g. All rights reserved.
//

#import "ViewController.h"
#import "NetworkManger.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [NetworkManger GET:@"http://172.18.26.196/get.php?page=1" success:^(id result) {
        NSLog(@"result:%@",result);
    } failure:^(NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

//
//  NetworkManger.h
//  UI11_网络封装
//
//  Created by lanou3g on 17/8/17.
//  Copyright © 2017年 lanou3g. All rights reserved.
//

#import 

typedef void (^Seccess)(id result);
typedef void (^Failure)(NSError *error);

@interface NetworkManger : NSObject

+ (void)GET:(NSString *)URLString success:(Seccess)success failure:(Failure)failure;

@end

//
//  NetworkManger.m
//  UI11_网络封装
//
//  Created by lanou3g on 17/8/17.
//  Copyright © 2017年 lanou3g. All rights reserved.
//

#import "NetworkManger.h"

@implementation NetworkManger

+ (void)GET:(NSString *)URLString success:(Seccess)success failure:(Failure)failure {
    //URLString中可能含有中文等网络地址不允许出现的字符,需要做一个编码转化
    URLString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:URLString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error) {
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                success(result);
            } else {
                failure(error);
            }
        });
        
    }];
    [dataTask resume];
}

@end

你可能感兴趣的:(UI11_网络封装(17-08-17))