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

@interface ViewController ()
{
    // AFN的客户端,使用基本地址初始化,同时会实例化一个操作队列,以便于后续的多线程处理
    AFHTTPClient    *_httpClient;
    
    // 下载操作
    AFHTTPRequestOperation *_downloadOperation;
    
    NSOperationQueue *_queue;
}

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@end

@implementation ViewController
/*
 关于文件下载,在Documents中保存的文件,一定是要应用程序产生的文件或者数据
 没有明显提示用户下载到本地的文件不能保存在Docuemnts中!
 
 
 */

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSURL *url = [NSURL URLWithString:@"http://192.168.3.251/~apple/itcast"];
    _httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
    
    _queue = [[NSOperationQueue alloc] init];
}

#pragma mark - 文件上传
- (IBAction)uploadImage
{
    /*
     此段代码如果需要修改,可以调整的位置
     
     1. 把upload.php改成网站开发人员告知的地址
     2. 把file改成网站开发人员告知的字段名
     */
    // 1. httpClient->url
    
    // 2. 上传请求POST
    NSURLRequest *request = [_httpClient multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 在此位置生成一个要上传的数据体
        // form对应的是html文件中的表单
        /*
         参数
         1. 要上传的[二进制数据]
         2. 对应网站上[upload.php中]处理文件的[字段"file"]
         3. 要保存在服务器上的[文件名]
         4. 上传文件的[mimeType]
         */
        UIImage *image = [UIImage imageNamed:@"头像1"];
        NSData *data = UIImagePNGRepresentation(image);
        
        // 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
        // 要解决此问题,
        // 可以在上传时使用当前的系统事件作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
    }];
    
    // 3. operation包装的urlconnetion
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"上传完成");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"上传失败->%@", error);
    }];
    
    [_httpClient.operationQueue addOperation:op];
}

- (IBAction)pauseResume:(id)sender
{
    // 关于暂停和继续,AFN中的数据不是线程安全的
    // 如果使用操作的暂停和继续,会使得数据发生混乱
    // 不建议使用此功能。
    // 有关暂停和后台下载的功能,NSURLSession中会介绍。
    if (_downloadOperation.isPaused) {
        [_downloadOperation resume];
    } else {
        [_downloadOperation pause];
    }
}

#pragma mark 下载
- (IBAction)download
{
    // 1. 建立请求
    NSURLRequest *request = [_httpClient requestWithMethod:@"GET" path:@"download/Objective-C2.0.zip" parameters:nil];
    
    // 2. 操作
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
    _downloadOperation = op;
    
    // 下载
    // 指定文件保存路径,将文件保存在沙盒中
    NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [docs[0] stringByAppendingPathComponent:@"download.zip"];
    
    op.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
    
    // 设置下载进程块代码
    /*
     bytesRead                      当前一次读取的字节数(100k)
     totalBytesRead                 已经下载的字节数(4.9M)
     totalBytesExpectedToRead       文件总大小(5M)
     */
    [op setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        
        // 设置进度条的百分比
        CGFloat precent = (CGFloat)totalBytesRead / totalBytesExpectedToRead;
        NSLog(@"%f", precent);
        
        _progressView.progress = precent;
    }];
    
    // 设置下载完成操作
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        // 下载完成之后,解压缩文件
        /*
         参数1:要解结压缩的文件名及路径 path - > download.zip
         参数2:要解压缩到的位置,目录    - > document目录
         */
        [SSZipArchive unzipFileAtPath:path toDestination:docs[0]];
        
        // 解压缩之后,将原始的压缩包删除
        // NSFileManager专门用于文件管理操作,可以删除,复制,移动文件等操作
        // 也可以检查文件是否存在
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        
        // 下一步可以进行进一步处理,或者发送通知给用户。
        NSLog(@"下载成功");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载失败");
    }];
    
    // 启动下载
    [_httpClient.operationQueue addOperation:op];
 }

#pragma mark 检测网路状态
/*
 AFNetworkReachabilityStatusUnknown          = -1,  未知
 AFNetworkReachabilityStatusNotReachable     = 0,   未连接
 AFNetworkReachabilityStatusReachableViaWWAN = 1,   3G
 AFNetworkReachabilityStatusReachableViaWiFi = 2,   无线连接
 */
- (IBAction)checkNetwork:(id)sender
{
    // 1. AFNetwork 是根据是否能够连接到baseUrl来判断网络连接状态的
    // 提示:最好使用门户网站来判断网络连接状态。
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    
    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:url];
    _httpClient = client;
    
    [_httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

// 之所以区分无线和3G主要是为了替用户省钱,省流量
        // 如果应用程序占流量很大,一定要提示用户,或者提供专门的设置,仅在无线网络时使用!
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"无线网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"3G网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"未连接");
                break;
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知错误");
                break;
        }
    }];
}

/**
 官方建议AFN的使用方法
 
 1. 定义一个全局的AFHttpClient:包含有
    1> baseURL
    2> 请求
    3> 操作队列 NSOperationQueue
 2. 由AFHTTPRequestOperation负责所有的网络操作请求
 
 */
#pragma mark - Actions
- (void)loadJSON1
{
    // 1. NSURL
    NSURL *url = [NSURL URLWithString:@""];
    
    // 2. NSURLRequest
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 3. NSURLConnection
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (connectionError != nil) {
            NSLog(@"%@", connectionError.localizedDescription);
        } else {
            NSError *error = nil;
            
            NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
            
            if (error != nil) {
                NSLog(@"%@", error.localizedDescription);
            } else {
                NSLog(@"%@", array);
            }
        }
    }];
}

#pragma mark 加载JSON
- (IBAction)loadJSON
{
    // 1. NSURLRequest
    NSURLRequest *request = [_httpClient requestWithMethod:@"GET" path:@"videos.php?format=json" parameters:nil];
    
    // 2. 连接
    AFJSONRequestOperation *op = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSArray *JSON) {
        
        // 成功之后,直接使用反序列化出来的结果即可。
        NSLog(@"%@", JSON);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        // 1> 网络访问获取数据出错
        // 2> JSON的反序列化出错
        
        NSLog(@"%@ %@", error, JSON);
    }];
    
    // 3. 将操作添加到队列,开始多线程操作
    // 将操作添加到队列或者start,操作就会启动
    [_httpClient.operationQueue addOperation:op];
//    [_queue addOperation:op];
//    [op start];
}

- (IBAction)loadXML:(id)sender
{
}

IOS - AFN的更多相关文章

  1. IOS AFN (第三方请求)

    什么是AFN全称是AFNetworking,是对NSURLConnection.NSURLSession的一层封装虽然运行效率没有ASI高,但是使用比ASI简单在iOS开发中,使用比较广泛 AFN的g ...

  2. IOS AFN请求 总结

    一.2大管理对象 1.AFHTTPRequestOperationManager* 对NSURLConnection的封装 2.AFHTTPSessionManager* 对NSURLSession的 ...

  3. iOS AFN向接口端传递JSON数据

    NSDictionary *body = @{@"snippet": @{@"topLevelComment":@{@"snippet":@ ...

  4. iOS AFNetworking内存泄漏处理方法

    iOS AFN内存泄漏处理方法 细心的你是否也发现AFN的内存泄漏的问题了呢. 在这里给大家提供一个解决AFN内存泄漏的方法. 单例解决AFN内存泄漏 + (AFHTTPSessionManager ...

  5. iOS 之 HTTPS集成实战应用

    临时想起来忘记把项目中用到的https集成整理收藏起来,以备后续不时之需.新手一般了解如下步骤即可: 1. HTTP 和 HTTPS 基本知识和学习 http://www.cnblogs.com/xi ...

  6. iOS开发之AFN的基本使用

    本篇将从四个方面对iOS开发中经常使用到的AFNetworking框架进行讲解: 一.什么是 AFN 二.为什么要使用 AFN 三.AFN 怎么用 三.AFN和ASI的区别 一.什么是 AFN AFN ...

  7. iOS开发——网络篇——NSURLSession,下载、上传代理方法,利用NSURLSession断点下载,AFN基本使用,网络检测,NSURLConnection补充

    一.NSURLConnection补充 前面提到的NSURLConnection有些知识点需要补充 NSURLConnectionDataDelegate的代理方法有一下几个 - (void)conn ...

  8. IOS开发 AFN和ASI

    做项目有一段时间了,项目过程中处理网络请求难免的,而对于选择第三方来处理网络请求肯定是个明智的选择! AFNetworking和ASIHTTPRequest   这两个第三方该如何选择       我 ...

  9. iOS应用将强制使用HTTPS安全加密-afn配置https(190926更新)

    WWDC 2016苹果开发者大会上,苹果在讲解全新的iOS10中提到了数据安全这一方面,并且苹果宣布iOS应用将从2017年1月起启用名为App Transport Security的安全传输功能. ...

随机推荐

  1. iOS: Crash文件解析(一)

    iOS Crash文件的解析(一) 开发程序的过程中不管我们已经如何小心,总是会在不经意间遇到程序闪退.脑补一下当你在一群人面前自信的拿着你的App做功能预演的时候,流畅的操作被无情地Crash打断. ...

  2. C# 中excel操作

    c#中设置Excel单元格格式    1.全表自动列宽 mysheet.Cells.Select(); mysheet.Cells.Columns.AutoFit(); 2.合并    excelRa ...

  3. POJ 2155 Matrix

    二维树状数组....                          Matrix Time Limit: 3000MS   Memory Limit: 65536K Total Submissio ...

  4. hdu.1104.Remainder(mod && ‘%’ 的区别 && 数论(k*m))

    Remainder Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total ...

  5. jQuery的$.ajax示例

    $.ajax({ url: 'index.php?module=products&submod=product_experience_manage&method=ajaxGetSele ...

  6. Objective-C上地球坐标系到火星坐标系转换算法

    Objective-C上地球坐标系到火星坐标系转换算法 http://blog.csdn.net/zhaoxy_thu/article/details/17033347

  7. AMD正式公布第七代桌面级APU AM4新接口

    导读 本月5日,AMD正式公布了入门级的第七代桌面级APU为Bristol Ridge,在性能和能效方面较上一代产品拥有显著提升.AMD同时确认Zen处理器和新APU(Bristol Ridge)都将 ...

  8. phpcms 搜索结果页面栏目不显示解决 方法

    头部文件 定义 <?php if(!isset($CATEGORYS)) { $CATEGORYS = getcache('category_content_'.$siteid,'commons ...

  9. SpringMVC基础入门

    一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于SpringMVC的配置 1 2 3 4 5 6 ...

  10. 18.1---不用加号的加法(CC150)

    1,自己写的又长又臭的代码,也能AC,但是太丑了.主要是通过二进制来算. public static int addAB(int a, int b){ int res = 0; String str1 ...