iOS 網絡請求封裝類

    此類名爲CWSingleSample,只爲方便本身修改, 添加方法所記錄!ios

 

  CWSingleSample.h服務器

//
//  CWSingleSample.h
//  students
//
//  Created by ZKSoft on 14/11/13.
//  Copyright (c) 2014年 ZK. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"
#import "MBProgressHUD.h"
#import "AFHTTPRequestOperation.h"
#import "ASIHTTPRequest.h"
//請求成功時的回調block
typedef void (^getDataBlock)(id data);
//請求失敗時的回調block
typedef void (^getErrorBlock)(NSError* error);
//上傳文件時的回調block
typedef void (^getFileBlock)(NSString* fileName,id data);
//接口枚舉
typedef enum {
   CWSMSSEND=0,//短信驗證碼發送
   CWUSERREGISTER,//用戶註冊
   CWUSERLOGIN,//用戶登陸
  CWPASSWORDDEAL,//密碼修改/找回密碼
   CWUPDATEUSERINFO,//用戶信息修改
   CWADDUPDATEDRIVER,//駕駛員信息修改/新增
   CWQUERYDRIVER,//駕駛員信息查詢
   CWDELETEDRIVER,//刪除駕駛員信息
   CWAPPLYLOAN,//貸款申請
   CWQUERYLOANINFO,//貸款信息列表查詢
   CWDELETELOANINFO ,//撤銷貸款請求
    CWUPLOADRELATIVE//通信錄上傳
} WKNetInterface;


@interface CWSingleSample : NSObject<ASIHTTPRequestDelegate>
+(CWSingleSample *)sharedSingleSample:(UIViewController *)myViewController;

@property (nonatomic,strong) MBProgressHUD* ssHUD;
@property (nonatomic,strong) UIViewController *myViewController;
/**
 *請求簡化版
 */
-(void)myNetWork:(WKNetInterface)myInterface withUrl:(NSString *)strUrl withFinish:(getDataBlock)dataBlock;
-(void)myNetWork:(WKNetInterface)myInterface withUrl:(NSString *)strUrl withValue:(NSDictionary *)value withFinish:(getDataBlock)dataBlock;

/**
 *統一的http請求,參數:請求的標示名稱,請求的參數串,請求成功的回調,請求失敗的回調
 */
-(void)myNetWork:(WKNetInterface)myInterface withValue:(NSDictionary *)value withUrl:(NSString *)strUrl withFinish:(getDataBlock)dataBlock withError:(getErrorBlock)errorBlock;
/**
 * 上傳文件
 * @param flag 是否須要保存數據
 */
-(void)myUploadFile:(UIImage *)uploadImage withFinish:(getFileBlock)finishBlock withError:(getErrorBlock)errorBlock withFlag:(BOOL)flag;

/**
 *上傳圖片
 */
-(void)myUploadFile:(UIImage *)uploadImage withFinish:(getFileBlock)finishBlock withError:(getErrorBlock)errorBlock withFlag:(BOOL)flag;

/**
 * 文件上傳
 * @param thUpFilePath 文件路徑
 * @param url 服務器地址
 * @param finishBlock 請求成功
 * @param errorBlock 請求錯誤
 */
-(void)myUploadFile:(NSString *)theUpFilePath withFileUrl:(NSString *)url withFinish:(getFileBlock)finishBlock withError:(getErrorBlock)errorBlock;

/**
 *語音文件下載
 * @param url 請求地址
 * @param path 下載文件存放的路徑
 */
-(void)downLoadVoiceUrl:(NSString *)url withDownloadPath:(NSString *)path;
@end

 

 CWSingleSample.m網絡

//
//  CWSingleSample.m
//  students
//
//  Created by ZKSoft on 14/11/13.
//  Copyright (c) 2014年 ZK. All rights reserved.
//

#import "CWSingleSample.h"
 
@implementation CWSingleSample
static CWSingleSample *sharedSingleSample=nil;
+(CWSingleSample *)sharedSingleSample:(UIViewController *)myViewController{
    
    @synchronized(self)
    {
        if (!sharedSingleSample){
            sharedSingleSample = [[CWSingleSample alloc] init];
            sharedSingleSample.myViewController=myViewController;
            //初始化進度框,置於當前的View當中
            sharedSingleSample.ssHUD = [[MBProgressHUD alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
            [[[[UIApplication sharedApplication] delegate] window] addSubview:sharedSingleSample.ssHUD];
            
            //若是設置此屬性則當前的view置於後臺
            sharedSingleSample.ssHUD.dimBackground = YES;
            
        }
        return sharedSingleSample;
    }
}

-(void)myNetWork:(WKNetInterface)myInterface withUrl:(NSString *)strUrl withFinish:(getDataBlock)dataBlock{
    [self myNetWork:myInterface withValue:nil withUrl:strUrl withFinish:dataBlock withError:nil];
}
-(void)myNetWork:(WKNetInterface)myInterface withUrl:(NSString *)strUrl withValue:(NSDictionary *)value withFinish:(getDataBlock)dataBlock{
    [self myNetWork:myInterface withValue:value withUrl:strUrl withFinish:dataBlock withError:nil];
}
-(void)myNetWork:(WKNetInterface)myInterface withValue:(NSDictionary *)value withUrl:(NSString *)strUrl withFinish:(getDataBlock)dataBlock withError:(getErrorBlock)errorBlock{
    //配置請求接口
    NSArray *interTemp=@[
                        @"smsSend",//短信驗證碼發送
                        @"userRegister",//用戶註冊
                        @"userLogin",//用戶登陸
                        @"passwordDeal",//密碼修改/找回密碼
                        @"updateUserInfo",//用戶信息修改
                        @"addUpdateDriver",//駕駛員信息修改/新增
                        @"queryDriver",//駕駛員信息查詢
                        @"deleteDriver",//刪除駕駛員信息
                        @"applyLoan",//貸款申請
                        @"queryLoanInfo",//貸款信息列表查詢
                        @"deleteLoanInfo",//撤銷貸款請求
                        @"uploadRelative"//通信錄上傳
                         ];
    value=value==nil?@{}:value;
    //配置請求
    NSURL *requestUrl=[NSURL URLWithString:CWBaseURLString];
    AFHTTPClient *client=[[AFHTTPClient alloc] initWithBaseURL:requestUrl];
    
    if (myInterface==CWSMSSEND || myInterface==CWUSERREGISTER || myInterface==CWUSERLOGIN || myInterface==CWPASSWORDDEAL || myInterface==CWUPDATEUSERINFO || myInterface==CWADDUPDATEDRIVER || myInterface==CWQUERYDRIVER || myInterface==CWDELETEDRIVER || myInterface == CWAPPLYLOAN || myInterface==CWQUERYLOANINFO ||myInterface==CWDELETELOANINFO ||myInterface ==CWUPLOADRELATIVE) {
        [CWSS.ssHUD setLabelText:@"加載中"];
        [CWSS.ssHUD show:YES];
    }
 
         if (YES) {//post
        NSLog(@"post");
        [client postPath:[NSString stringWithFormat:@"TaxiLoanGate/LoanCtrlServlet?action=%@%@",[interTemp objectAtIndex:myInterface],strUrl] parameters:value success:^(AFHTTPRequestOperation *operation,id responseObject){
                [CWSS.ssHUD hide:YES];
            NSLog(@"url---%@",[[operation request] URL]);
            if (dataBlock) {
                id tempData=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                if ([[tempData objectForKey:@"success"] isEqualToString:@"0000"]) {
                    dataBlock(tempData);
                    
                }else{
//                   dataBlock(tempData);
                    if (myInterface==CWUSERLOGIN  || myInterface==CWUSERREGISTER ||myInterface==CWPASSWORDDEAL || myInterface==CWAPPLYLOAN || myInterface==CWDELETELOANINFO || myInterface==CWADDUPDATEDRIVER ||myInterface==CWDELETEDRIVER){
                        [cwutil myAlertView:[tempData objectForKey:@"respinfo"]];
                       
                    }else{
                        NSLog(@"%d--%@",myInterface,[[operation request] URL]);
                    }
                }
                
            }
            [CWSS.ssHUD hide:YES];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [CWSS.ssHUD hide:YES];
            if (errorBlock) {
                errorBlock(error);
            }else{
                NSLog(@"%d--%@--%@",myInterface,[[operation request] URL],error);
            }
        }];
    }else{//get
        [client getPath:[NSString stringWithFormat:@"TaxiLoanGate/LoanCtrlServlet?action=%@%@",[interTemp objectAtIndex:myInterface],strUrl] parameters:value success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [CWSS.ssHUD hide:YES];
            if (dataBlock) {
                dataBlock([NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil]);
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [CWSS.ssHUD hide:YES];
            if (errorBlock) {
                errorBlock(error);
            }else{
                NSLog(@"%d-><-%@--%@",myInterface,[[operation request] URL],error);
            }
        }];
    }
}

/**
 * 上傳圖片
 */
-(void)myUploadFinish:(getFileBlock)finishBlock withError:(getErrorBlock)errorBlock{
    NSURL *requestUrl=[NSURL URLWithString:[[CWBaseURLString stringByAppendingFormat:@"RemoteUpload.aspx?vercode=123456&operation=iosupload"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    AFHTTPClient *httpClient=[[AFHTTPClient alloc] initWithBaseURL:requestUrl];
    NSData *imageData=UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
    
    NSMutableURLRequest *request=[httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData){
        [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpg"];
    }];
    
    AFHTTPRequestOperation *operation=[[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setUploadProgressBlock:^(NSUInteger bytesWrittrn,long long totalBytesWritten,long long totalBytesExpectedToWrite){
        NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
    }];
    [operation start];
}

/**
 * 上傳文件
 * @param flag 是否須要保存數據
 */
-(void)myUploadFile:(UIImage *)uploadImage withFinish:(getFileBlock)finishBlock withError:(getErrorBlock)errorBlock withFlag:(BOOL)flag{
    
    NSURL *requestUrl=[NSURL URLWithString:[[CWBaseURLString stringByAppendingString:@""] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    [CWSS.ssHUD setLabelText:@"正在上傳"];
    [CWSS.ssHUD show:YES];
    AFHTTPClient *httpClient=[[AFHTTPClient alloc] initWithBaseURL:requestUrl];
    
    NSMutableURLRequest *request=[httpClient multipartFormRequestWithMethod:@"POST" path:@"/RemoteUpload.ashx?vercode=123456&operation=iosupload&Filename=head.png" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>formData){
        NSData *data=UIImageJPEGRepresentation(uploadImage, 0.4);
        NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory=[paths objectAtIndex:0];
        
        ///上傳頭像
        NSString *savedImagePath=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"temp_head.jpg"]];
        [data writeToFile:savedImagePath atomically:NO];
        
        [formData appendPartWithFileData:data name:@"filename" fileName:savedImagePath mimeType:@"image/jpg"];
        
    }];
    
    AFHTTPRequestOperation *operation=[[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,id responseObject){
        if (finishBlock) {
            finishBlock([[operation userInfo] objectForKey:@"filename"],[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil]);
            
//            if (flag==YES) {
//                NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingAllowFragments error:nil];
//                NSLog(@"dic---%@",[dic objectForKey:@"data"]);
//                if ([[ZKNSUserDefaults initUserDefaults].userDefaults objectForKey:UPLOADIMAGE]) {
//                    [ZKNSUserDefaults deleteUserDefaultsData:UPLOADIMAGE];
//                }
//                //保存頭像
//                [ZKNSUserDefaults createUserDefaultDB:UPLOADIMAGE getArrayData:[dic objectForKey:@"data"]];
//            }
            NSLog(@"上傳成功");
            [CWSS.ssHUD setLabelText:@"上傳成功"];
            [CWSS.ssHUD hide:YES afterDelay:2.0f];
        }
    } failure:^(AFHTTPRequestOperation *operation,NSError *error){
        if (errorBlock) {
            errorBlock(error);
            NSLog(@"上傳失敗");
            [CWSS.ssHUD setLabelText:@"上傳失敗"];
            [CWSS.ssHUD hide:YES afterDelay:2.0f];
        }
    }];
    [httpClient enqueueHTTPRequestOperation:operation];
}

/**
 * 上次用於語音文件的上傳
 */
-(void)myUploadFile:(NSString *)theUpFilePath withFileUrl:(NSString *)url withFinish:(getFileBlock)finishBlock withError:(getErrorBlock)errorBlock{
    NSURL *requestUrl=[NSURL URLWithString:[[CWBaseURLString stringByAppendingString:@""] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    AFHTTPClient * client=[[AFHTTPClient alloc] initWithBaseURL:requestUrl];
    NSMutableURLRequest *fileUpRequest=[client multipartFormRequestWithMethod:@"POST" path:[NSString stringWithFormat:@"ichat.aspx?vercode=123456%@",url] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSError *error;
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:theUpFilePath isDirectory:NO] name:@"file" fileName:@"textMusic.mp3" mimeType:@"audio/mp3" error:&error];
        NSLog(@"errorBlock---%@",error);
    }];
    
    AFHTTPRequestOperation *fileUploadOp=[[AFHTTPRequestOperation alloc] initWithRequest:fileUpRequest];
    [fileUploadOp setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"upload finish ---%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error---%@",error);
    }];
    
    [client enqueueHTTPRequestOperation:fileUploadOp];
}

/**
 *語音文件下載
 * @param url 請求地址
 * @param path 下載文件存放的路徑
 */
-(void)downLoadVoiceUrl:(NSString *)url withDownloadPath:(NSString *)path{
    NSURL *urlString = [NSURL URLWithString:[NSString stringWithFormat:@"%@Download.ashx?vercode=123456%@",CWBaseURLString,url]];
    
    NSLog(@"url---%@",urlString);
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:urlString];
    request.delegate=self;
    //當request完成時,整個文件會被移動到這裏
    [request setDownloadDestinationPath:path];
    //這個文件已經被下載了一部分
    //                        [request setTemporaryFileDownloadPath:[NSString stringWithFormat:@"%@%@",NSTemporaryDirectory(),[[[[[data objectForKey:@"data"] objectForKey:@"MsgList"][i] objectForKey:@"Content"] componentsSeparatedByString:@":"][2] stringByReplacingOccurrencesOfString:@"]" withString:@""]]];
    [request setAllowResumeForFileDownloads:YES];//是否容許斷點下載
    [request startSynchronous];
    
    NSLog(@"path---%@",path);
}

#pragma mark ASIHTTPRequestDelegate
-(void)requestFailed:(ASIHTTPRequest *)request{
    NSLog(@"下載失敗");

}
-(void)requestFinished:(ASIHTTPRequest *)request{
    NSLog(@"下載成功");

}


@end

 

 在pch文件中須要定義常量:app

#define CWBaseURLString @"http://172.16.128.174:8080/"
//網絡單例類的調用
#define CWSS [CWSingleSample sharedSingleSample:sharedSingleSample.myViewController]

 

 

                                                                                              這次修改:2015-3-27    未完待續...ide

相關文章
相關標籤/搜索