zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

iOS AFNetwork实现Http相关操作(NetReachable、Get、Post、Upload、Download)

iosHTTP 实现 操作 相关 get post Download
2023-09-11 14:22:56 时间

AFNetworking是一个轻量级的iOS网络通信类库。它建立在NSURLConnection和NSOperation等类库的基础上,让很多网络通信功能的实现变得十分简单。它支持HTTP请求和基于REST的网络服务(包括GET、POST、 PUT、DELETE等)。支持ARC。

Github地址:https://github.com/AFNetworking/AFNetworking

当前的AFNetworking版本为 v3.1.0。

特别指出 v3.x 与 v2.x 的区别:Xcode 7+ is required.NSURLConnectionOperation support has been removed

(网上2015年千篇一律的AFNetworking代码都是基于 v2.x 的,到 v3.x 有很多方法deprecated了。所以建议新手还是自己手打一遍比较好)

以下代码为 csdn "chy龙神" 原创,基于XCode7、iOS9.0、Mac OS 10.11

//
//  ViewController.m
//  AFNetworkDemo
//
//  Created by 555chy on 6/27/16.
//  Copyright © 2016 555chy. All rights reserved.
//

#import "ViewController.h"
#import "AFNetworking.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

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

/*
 
 1. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]
    所有的网络请求,均由manager发起
 2. 注意:默认提交请求的数据是二进制的,返回格式是JSON
 3. 请求格式
    AFHttpRequestSerializer                 二进制
    AFJSONRequestSerializer                 JSON
    AFPropertyListRequestSerializer         PList(一种特殊的XML,但解析起来相对容易)
 4. 返回格式
    AFHTTPResponseSerializer                二进制
    AFJSONResponseSerialializer             JSON
    AFXMLParserResponseSerializer           XML,只能返回XMLParser,还需要自己通过代理方法解析
    AFXMLDocumentResponseSerializer         Mac OS X
    AFPropertyListResponseSerializerPList   PList
    AFImageResponseSerializer               Image
    AFCompoundResponseSerializer            组合
 */

#pragma mark - 检测网络连接
-(void)networkReachable {
    //sharedManager表示单例
    AFNetworkReachabilityManager *networkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [networkReachabilityManager startMonitoring];
    [networkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        /*
         typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
         AFNetworkReachabilityStatusUnknown          = -1,  未知
         AFNetworkReachabilityStatusNotReachable     = 0,   无连接
         AFNetworkReachabilityStatusReachableViaWWAN = 1,   2G、3G、4G
         AFNetworkReachabilityStatusReachableViaWiFi = 2,   Wifi局域网
         };
         */
        NSString *statusStr;
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                statusStr = @"AFNetworkReachabilityStatusUnknown";
                break;
            case AFNetworkReachabilityStatusNotReachable:
                statusStr = @"AFNetworkReachabilityStatusNotReachable";
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                statusStr = @"AFNetworkReachabilityStatusReachableViaWWAN";
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                statusStr = @"AFNetworkReachabilityStatusReachableViaWiFi";
                break;
        }
        NSLog(@"networkReachable %@ = %ld", statusStr, status);
    }];
}

#pragma mark - 上传(下载)文件
/*
 上传和下载雷同,故这里只介绍下载
 (1)上传:@"http://example.com/upload"
 - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
 fromFile:(NSURL *)fileURL
 progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
 completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError  * _Nullable error))completionHandler;
 (2)下载:@"http://example.com/download.zip"
 - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
 progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
 destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
 completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
 */
//urlStr这个参数可以包含中文
-(void)sessionDownload:(NSString *) urlStr {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    //对url进行urlEncode编码(%编码)
    //NS_DEPRECATED(10_0, 10_11, 2_0, 9_0, "Use -stringByAddingPercentEncodingWithAllowedCharacters: instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.");
    NSString *percentEscapesUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *percentEncodeUrlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
    NSLog(@"sessionDownload stringByAddingPercentEscapesUsingEncoding = %@", percentEscapesUrlStr);
    NSLog(@"sessionDownload stringByAddingPercentEncodingWithAllowedCharacters = %@", percentEncodeUrlStr);
    NSURL *url = [NSURL URLWithString:percentEncodeUrlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *downLoadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        //fraction分数,这里表示百分比下载进度
        double downloadFraction = downloadProgress.fractionCompleted;
        NSString *downloadDescription = downloadProgress.localizedDescription;
        NSString *downloadAdditionalDescription = downloadProgress.localizedAdditionalDescription;
        NSLog(@"sessionDownload fractionCompleted = %lf, localizedDescription = %@, localizedAdditionalDescription = %@", downloadFraction, downloadDescription, downloadAdditionalDescription);
    
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSString *suggestedFileName = response.suggestedFilename;
        //保存路径和文件名
        NSLog(@"sessionDownload targetPath = %@, response = %@)", targetPath, suggestedFileName);
        NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        NSString *path = [cacheDir stringByAppendingPathComponent:suggestedFileName];
        //如果保存的地址是网络地址,用URLWithString
        NSURL *webUrl = [NSURL URLWithString:path];
        NSURL *fileUrl = [NSURL fileURLWithPath:path];
        NSLog(@"sessionDownload webUrl = %@, fileUrl = %@", webUrl, fileUrl);
        return fileUrl;
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        NSLog(@"sessionDownload response = %@, filePath = %@, error = %@", response, filePath, error);
    
    }];
    //最后的resume是为了防止被ARC回收
    [downLoadTask resume];
}

#pragma mark - Get、POST通过参数上传,通过返回数据下载
-(void)sessionGet:(NSString *)urlStr parameters:(NSDictionary *) params {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURL *url = [NSURL URLWithString:urlStr];

    /*
     requestMethod有GET、POST等
     例如:
     NSString *URLString = @"http://example.com";
     NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
     用默认请求方法的话使用的是GET
     NSURLRequest *request = [NSURLRequest requestWithURL:url];
     */
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:urlStr parameters:params error:nil];
    
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
       
        NSLog(@"loginByGet response = %@, responseObject = %@, error = %@", response, responseObject, error);
        
    }];
    [dataTask resume];
}

@end