BLOCK封装带菊花的网络请求

时间:2022-02-17 21:56:33
#import <Foundation/Foundation.h>
@class HttpRequestManager;

typedef void(^httpRequestBlock) (HttpRequestManager *manager);

@interface HttpRequestManager : NSObject

@property(nonatomic,strong)NSData *data;

-(id)initWithUrlString:(NSString *)url  andBlock:(httpRequestBlock)block;

@end
#import "HttpRequestManager.h"

#import "AFNetworking.h"

#import "SVProgressHUD.h"
@implementation HttpRequestManager

- (id)initWithUrlString:(NSString *)url andBlock:(httpRequestBlock)block{
    
    if (self=[super init]) {
        
        [self  requestDataWithString:url andBlock:block];
    }
    
    return self;
}

-(void)requestDataWithString:(NSString *)url  andBlock:(httpRequestBlock)tempBlock{
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [SVProgressHUD  showWithStatus:@"正在加载" maskType:SVProgressHUDMaskTypeBlack];
    
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        self.data = responseObject;
        
        [SVProgressHUD  showSuccessWithStatus:@"OK" maskType:SVProgressHUDMaskTypeBlack];
        
        tempBlock(self);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD  showErrorWithStatus:@"网速有问题"];
        
        NSLog(@"%@",error.localizedDescription);
        
    }];
    
}
@end
//使用实例

/*
@property(nonatomic,strong)HttpRequestManager *manager;
_manager = [[HttpRequestManager alloc]initWithUrlString:path andBlock:^(HttpRequestManager *manager) {
    
    [cache  saveDataWith:manager.data andNameString:path];
    
    [self  serializationData:manager.data];
}];
*/