IOS开发之网络开发工具
IOS开发之网络开发工具
做移动端开发 常常会涉及到几个模块:1、网络检測 2、网络请求get和post请求 3、文件上传 4、文件下载 5、断点续传
如今将这些一一分享给大家 ,也欢迎大家一起学习和讨论 本样例採用AFNetWorking框架
网络检測:
#pragma mark - Reachability Management (iOS 6-7)
//网络监听(用于检測网络能否够链接。此方法最好放于AppDelegate中。能够使程序打开便開始检測网络)
- (void)reachabilityManager
{
    //打开网络监听
    [manager.reachabilityManager startMonitoring];
    
    //监听网络变化
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
                
            //当网络不可用(无网络或请求延时)
            case AFNetworkReachabilityStatusNotReachable:
                break;
                
            //当为手机蜂窝数据网和WiFi时
            case AFNetworkReachabilityStatusReachableViaWiFi:
            case AFNetworkReachabilityStatusReachableViaWWAN:
                break;
                
            //其他情况
            default:
                break;
        }
    }];
    
    //停止网络监听(若须要一直检測网络状态,能够不停止,使其一直执行)
    [manager.reachabilityManager stopMonitoring];
}
Get请求数据:
#pragma mark - GET Request (iOS 6-7)
//GET请求
- (void)methodGet
{
//致空请求
if (manager) {
manager = nil;
}
//创建请求
manager = [AFHTTPRequestOperationManager manager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData)。默觉得AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送GET请求
[manager GET:@"接口地址" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
NSLog(@"Success: %@", responseObject);
//请求成功(当解析器为AFHTTPResponseSerializer时)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
NSLog(@"Error: %@", error);
}];
}
POST请求:
#pragma mark - POST Request (iOS 6-7)
//POST请求
- (void)methodPost
{
//致空请求
if (manager) {
manager = nil;
}
//加入參数
NSDictionary *parameters = @{@"Key": @"Object",
@"Key": @"Object"};
//创建请求
manager = [AFHTTPRequestOperationManager manager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData)。默觉得AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送POST请求
[manager POST:@"接口地址" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
NSLog(@"Success: %@", responseObject);
//请求成功(当解析器为AFHTTPResponseSerializer时)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
NSLog(@"Error: %@", error);
}];
}
上传:
#pragma mark - Upload Request (iOS 6-7)
//上传(以表单方式上传。以图片为例)
- (void)methodUpload
{
//致空请求
if (manager) {
manager = nil;
}
//加入參数
NSDictionary *parameters = @{@"Key": @"Object",
@"Key": @"Object"};
//创建请求
manager = [AFHTTPRequestOperationManager manager];
//设置请求的解析器为AFHTTPResponseSerializer(用于直接解析数据NSData),默觉得AFJSONResponseSerializer(用于解析JSON)
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//发送POST请求。加入须要发送的文件,此处为图片
[manager POST:@"接口地址" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//加入图片。并对其进行压缩(0.0为最大压缩率。1.0为最小压缩率)
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"图片名字(注意后缀名)"], 1.0);
//加入要上传的文件。此处为图片
[formData appendPartWithFileData:imageData name:@"server放图片的參数名(Key)" fileName:@"图片名字" mimeType:@"文件类型(此处为图片格式。如image/jpeg)"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
//请求成功(当解析器为AFJSONResponseSerializer时)
NSLog(@"Success: %@", responseObject);
//请求成功(当解析器为AFHTTPResponseSerializer时)
// NSString *JSONString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// NSLog(@"success:%@", JSONString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//请求失败
NSLog(@"Error: %@", error);
}];
}
下载:
#pragma mark - Download Request (iOS 6-7)
//下载
- (void)methodDownload
{
//下载进度条
UIProgressView *downProgressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
downProgressView.center = CGPointMake(self.view.center.x, 220);
downProgressView.progress = 0;
downProgressView.progressTintColor = [UIColor blueColor];
downProgressView.trackTintColor = [UIColor grayColor];
[self.view addSubview:downProgressView];
//设置存放文件的位置(此Demo把文件保存在iPhone沙盒中的Documents目录中。
关于怎样获取文件路径,请自行搜索相关资料)
    //方法一
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *cachesDirectory = [paths objectAtIndex:0];
//    NSString *filePath = [cachesDirectory stringByAppendingPathComponent:@"文件名称"];
    //方法二
    NSString *filePath = [NSString stringWithFormat:@"%@/Documents/文件名称(注意后缀名)", NSHomeDirectory()];
    
    //打印文件保存的路径
    NSLog(@"%@",filePath);
    
    //创建请求管理
    operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"下载地址"]]];
    
    //加入下载请求(获取server的输出流)
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
    
    //设置下载进度条
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        
        //显示下载进度
        CGFloat progress = ((float)totalBytesRead) / totalBytesExpectedToRead;
        [downProgressView setProgress:progress animated:YES];
    }];
    
    //请求管理推断请求结果
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //请求成功
        NSLog(@"Finish and Download to: %@", filePath);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        //请求失败
        NSLog(@"Error: %@",error);
    }];
}
断点续传:
#pragma mark - Download Management (iOS 6-7)
//開始下载(断点续传)
- (void)downloadStart
{
[self methodDownload];
[operation start];
}
//暂停下载(断点续传)
- (void)downloadPause
{
[operation pause];
}
//继续下载(断点续传)
- (void)downloadResume
{
[operation resume];
}
IOS7特性特有上传和下载:
#pragma mark - Upload Request (iOS 7 only)
//上传(iOS7专用)
- (void)methodUploadFor7
{
//致空请求
if (sessionManager) {
sessionManager = nil;
}
//创建请求(iOS7专用)
sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//加入请求接口
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"上传地址"]];
//加入上传的文件
NSURL *filePath = [NSURL fileURLWithPath:@"本地文件地址"];
//发送上传请求
NSURLSessionUploadTask *uploadTask = [sessionManager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
//请求失败
NSLog(@"Error: %@", error);
} else {
//请求成功
NSLog(@"Success: %@ %@", response, responseObject);
}
}];
//開始上传
[uploadTask resume];
}
#pragma mark - Download Request (iOS 7 only)
//下载(iOS7专用)
- (void)methodDownloadFor7
{
//致空请求
if (sessionManager) {
sessionManager = nil;
}
//创建请求(iOS7专用)
sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//加入请求接口
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"下载地址"]];
//发送下载请求
NSURLSessionDownloadTask *downloadTask = [sessionManager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
//设置存放文件的位置(此Demo把文件保存在iPhone沙盒中的Documents目录中。关于怎样获取文件路径,请自行搜索相关资料)
NSURL *filePath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
return [filePath URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//下载完毕
NSLog(@"Finish and Download to: %@", filePath);
}];
//開始下载
[downloadTask resume];
}
源代码下载地址:http://download.csdn.net/detail/wangliang198901/7935199
                    
                
                
            
        
浙公网安备 33010602011771号