afn停止所有请求 ios
2016-12-12 15:05:00 weixin_34384915 阅读数 3

 

.h 文件

#import <Foundation/Foundation.h>

#define kTimeOutInterval 30  //请求超时时间

@interface SingletonClass : NSObject

+(SingletonClass *)shareSingletonClasss;

#pragma mark  Get 请求数据

-(void)GetParsingDataSourceWithUrl:(NSString *)url WithVC:(UIViewController * )VC success:(void(^)(id responseObject))success fail:(void(^)())fail;

#pragma mark  post上传数据

- (void)PostParsingDataSourceWithUrl:(NSString *)url parameters:(NSDictionary *)parameters  WithVC:(UIViewController * )VC success:(void(^)(id responseObject))success fail:(void(^)())fail;

 

#pragma mark 上传图片 Method

- (void)uploadWithUser:(NSString *)userId UrlString:(NSString *)urlString upImg:(UIImage *)upImg;

 

#pragma mark 下载

- (void)downLoadWithUrlString:(NSString * )urlString;

 

- (NSMutableDictionary * )getWillPOSTData;

//#pragma mark  GET  请求数据

//- (void)GetParsingDataSoucrceWithUrl:(NSString * )url success:(void(^)(id responseObject))success fail:(void(^)())fail;

@end

 

.m 文件 

 

 

//

//  SingletonClass.m

//  YuTongTianXia

//

//  Created by 合一网络 on 16/3/17.

//  Copyright © 2016年 合一网络. All rights reserved.

//

 

#import "SingletonClass.h"

#import "AppDelegate.h"

#import "GetIPAddress.h"

#import "LoginViewController.h"

 

 

@implementation SingletonClass

 

+(SingletonClass *)shareSingletonClasss{

    static SingletonClass * singletonClass = nil;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        singletonClass = [[SingletonClass alloc]init];

    });

    return singletonClass;

}

 

#pragma mark -  get 请求数据 Method

-(void)GetParsingDataSourceWithUrl:(NSString *)url WithVC:(UIViewController * )VC success:(void(^)(id responseObject))success fail:(void(^)())fail{

    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];

    manager.requestSerializer = [AFHTTPRequestSerializer serializer];

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    //超时时间

    manager.requestSerializer.timeoutInterval = kTimeOutInterval;

    

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];

    NSMutableDictionary * dic = [self getWillPOSTData];

    [manager GET:url parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {

        //这里可以获取到目前数据请求的进度

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {//请求成功

        

        //删除转义字符

        NSData *jsonData = [self deleteEscapeStringWithResponseObject:responseObject];

        //令牌异常的情况下跳转到登录界面

        [self JudgeTokenToLoginViewWithJsonData:jsonData WithVC:VC];

        //---------正常输入数据

       

        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];

            success(dict);

        

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {//请求失败

         [SVProgressHUD showErrorWithStatus:@"请求失败"];

        fail(error);

       

    }];

}

 

#pragma mark  - post 请求/上传数据  Method

- (void)PostParsingDataSourceWithUrl:(NSString *)url parameters:(NSDictionary *)parameters  WithVC:(UIViewController * )VC success:(void(^)(id responseObject))success fail:(void(^)())fail{

    AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc]init];

    

    manager.requestSerializer = [AFHTTPRequestSerializer serializer];

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];

    NSMutableDictionary * dic = [self getWillPOSTData];

    [dic addEntriesFromDictionary:parameters];

   [manager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

       

   } progress:^(NSProgress * _Nonnull uploadProgress) {

        // 这里可以获取到目前数据请求的进度

   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

       //请求成功

       NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];

       NSLog(@"--responseObjectStr----%@",str);

       //删除转义字符

       NSData *jsonData = [self deleteEscapeStringWithResponseObject:responseObject];

       //令牌异常的情况下跳转到登录界面

       [self JudgeTokenToLoginViewWithJsonData:jsonData WithVC:VC];

        //---------正常输入数据

           NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

           success(dict);

   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

       //请求失败

        [SVProgressHUD showErrorWithStatus:@"请求失败"];

       fail(error);

       

   }];

    

}

 

#pragma mark - 上传 Method

- (void)uploadWithUser:(NSString *)userId UrlString:(NSString *)urlString upImg:(UIImage *)upImg

{

     // 创建管理者对象

    AFHTTPSessionManager * manager  =[AFHTTPSessionManager manager];

     // 参数

    NSDictionary * param = @{@"user_id":userId};

    [manager POST:urlString parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        /******** 1.上传已经获取到的img *******/

        // 把图片转换成data

        NSData * data = UIImagePNGRepresentation(upImg);

         // 拼接数据到请求题中

        [formData appendPartWithFileData:data name:@"file" fileName:@"123.png" mimeType:@"image/png"];

        /******** 2.通过路径上传沙盒或系统相册里的图片 *****/

        //        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"文件地址"] name:@"file" fileName:@"1234.png" mimeType:@"application/octet-stream" error:nil];

        

    } progress:^(NSProgress * _Nonnull uploadProgress) {

        // 打印上传进度

        NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        //请求成功

        NSLog(@"请求成功:%@",responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        //请求失败

        NSLog(@"请求失败:%@",error);

         [SVProgressHUD showErrorWithStatus:@"请求失败"];

    }];

}

 

 

#pragma mark - 下载 Method

- (void)downLoadWithUrlString:(NSString * )urlString

{

     // 1.创建管理者对象

    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];

     // 2.设置请求的URL地址

    NSURL * url = [NSURL URLWithString:urlString];

    // 3.创建请求对象

    NSURLRequest * request = [NSURLRequest requestWithURL:url];

    // 4.下载任务

    NSURLSessionDownloadTask * task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

        //下载进度

        NSLog(@"当前下载进度为:%lf", 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);

    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

        //下载地址

         NSLog(@"默认下载地址%@",targetPath);

        // 设置下载路径,通过沙盒获取缓存地址,最后返回NSURL对象

        NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];

        return [NSURL fileURLWithPath:filePath]; // 返回的是文件存放在本地沙盒的地址

    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

        // 下载完成调用的方法

        NSLog(@"%@---%@", response, filePath);

    }];

    

    //启动下载任务

    [task resume];

}

 

#pragma mark - 删除转义字符

- (NSData * )deleteEscapeStringWithResponseObject:(NSData * )responseObject{

    NSString * str_Json = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];

    str_Json = [str_Json stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];

    str_Json = [str_Json stringByReplacingOccurrencesOfString:@"\r" withString:@""];

    str_Json = [str_Json stringByReplacingOccurrencesOfString:@"\n" withString:@""];

    str_Json = [str_Json stringByReplacingOccurrencesOfString:@"\t" withString:@"   "];

    str_Json = [str_Json stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@"   "];

    str_Json = [str_Json stringByReplacingOccurrencesOfString:@"&ldquo;" withString:@"“"];

    str_Json = [str_Json stringByReplacingOccurrencesOfString:@"&rdquo;" withString:@"”"];

    NSData * data = [str_Json dataUsingEncoding:NSUTF8StringEncoding];

    return data;

}

 

#pragma mark - 令牌异常的情况下跳转到登录界面

- (void)JudgeTokenToLoginViewWithJsonData:(NSData * )jsonData WithVC:(UIViewController * )VC{

    //令牌异常

    NSString * str = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

    if ([str isEqualToString:@"令牌错误!"] || [str isEqualToString:@"令牌过期!"]) {

 

        LoginViewController *login = [[LoginViewController alloc]init];

        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];

        [VC presentViewController:nav animated:YES completion:nil];

        return;

    }

 

}

 

#pragma mark - POST请求需要传入的参数

- (NSMutableDictionary * )getWillPOSTData{

    NSString * ipStr = [GetIPAddress getIPAddress:NO];

    

    NSDictionary * infoDic = [[NSBundle mainBundle] infoDictionary];

    NSString * currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];//当前版本号

    //     NSDictionary * parameters = @{@"qcmn_os":@"系统ios/android",@"qcmn_version":@"app版本号",@"qcmn_client_ip":@"客户端IP地址",@"qcmn_ts":@"测试数据/线上数据"};

    NSDictionary * parameters = @{@"qcmn_os":@"ios",@"qcmn_version":currentVersion,@"qcmn_client_ip":ipStr,@"qcmn_ts":TESTORONLINE};

    NSMutableDictionary * dic = [NSMutableDictionary dictionary];

    [dic addEntriesFromDictionary:parameters];

    return dic;

 

}

 

 

/*

 #pragma mark  GET  请求数据

 - (void)GetParsingDataSoucrceWithUrl:(NSString * )url success:(void(^)(id responseObject))success fail:(void(^)())fail

 {

 url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

 

 AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];

 

 manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];

 

 [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {

 //这里可以获取到目前数据请求的进度

 } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {//请求成功

 success(responseObject);

 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {//请求失败

  [SVProgressHUD showErrorWithStatus:@"请求失败"];

 fail(error);

 }];

 }

 */

 

转载于:https://www.cnblogs.com/LynnAIQ/p/6164561.html

2017-03-18 10:35:00 weixin_34112030 阅读数 5
一.项目中的网络交互都是基于AFN,要求AFN版本在3.0及其以上;

二.代码部分
设置AFN请求管理者的时候 添加 https ssl 验证。
// 1.获得请求管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 2.加上这个函数,https ssl 验证。
[manager setSecurityPolicy:[self customSecurityPolicy]];

// https ssl 验证函数

- (AFSecurityPolicy *)customSecurityPolicy {
    
    // 先导入证书 证书由服务端生成,具体由服务端人员操作
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"xxx" ofType:@"cer"];//证书的路径
    NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
         // allowInvalidCertificates 是否允许无效证书(也就是自建的证书),默认为NO
    // 如果是需要验证自建证书,需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名,默认为YES;
    //假如证书的域名与你请求的域名不一致,需把该项设置为NO;如设成NO的话,即服务器使用其他可信任机构颁发的证书,也可以建立连接,这个非常危险,建议打开。
    //置为NO,主要用于这种情况:客户端请求的是子域名,而证书上的是另外一个域名。因为SSL证书上的域名是独立的,假如证书上注册的域名是www.google.com,那么mail.google.com是无法验证通过的;当然,有钱可以注册通配符的域名*.google.com,但这个还是比较贵的。
    //如置为NO,建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    
    securityPolicy.pinnedCertificates = [[NSSet alloc] initWithObjects:cerData, nil];
    
    return securityPolicy;
}


三.关于证书 参考文章:http://www.2cto.com/Article/201510/444706.html
服务端给的是crt后缀的证书,其中iOS客户端用到的cer证书,是需要开发人员转换:
1.证书转换
在服务器人员,给你发送的crt证书后,进到证书路径,执行下面语句

openssl x509 -in 你的证书.crt -out 你的证书.cer -outform der

这样你就可以得到cer类型的证书了。双击,导入电脑。
2.证书放入工程
1、可以直接把转换好的cer文件拖动到工程中。
2、可以在钥匙串内,找到你导入的证书,单击右键,导出项目,就可以导出.cer文件的证书了

参考链接:http://www.jianshu.com/p/97745be81d64。
 
四.在info.plist去掉之前允许http加载的代码 就是删除下面的代码(么有的就省了这一步)
 <key>NSAppTransportSecurity</key>
	<dict>
 <key>NSAllowsArbitraryLoads</key>
 <true/>
	</dict>
一、
 2017年1月1日起所有提交到 App Store 的App必须强制开启 ATS。
 就是要求去掉 Info.plist 的 NSAllowsArbitraryLoads
 1.这要求所有通过APP发送的网络请求都需要https
 
 2.开启ATS,图片(例如图像的URL)等静态文件的url需要用https,否则会无法加载;
 
 3.对于H5,网页浏览和视频播放的行为,iOS 10 中新加入了NSAllowsArbitraryLoadsInWebContent 键。通过将它设置为 YES ,
 可以让你的 app 中的 WKWebView 和使用 AVFoundation 播放的在线视频不受 ATS 的限制。
 这也应该是绝大多数使用了相关特性的 app 的选择。但是坏消息是这个键在 iOS 9 中并不会起作用.
 
 4.iOS9中可以选择使用 NSExceptionDomains 来针对特定的域名开放 HTTP 应该要相对容易过审核。“需要访问的域名是第三方服务器,他们没有进行 HTTPS 对应”会是审核时的一个可选理由,但是这应该只需要针对特定域名,而非全面开放。如果访问的是自己的服务器的话,可能这个理由会无法通过。是需要在Info.plist 配置中的XML源码
     <key>NSAppTransportSecurity</key>
     <dict>
         <key>NSExceptionDomains</key>
         <dict>
             <key>XXX.com</key>
             <dict>
                 <!--适用于这个特定域名下的所有子域-->
                 <key>NSIncludesSubdomains</key>
                 <true/>
                 <!--扩展可接受的密码列表:这个域名可以使用不支持 forward secrecy 协议的密码-->
                 <key>NSExceptionRequiresForwardSecrecy</key>
                 <false/>
                 <!--允许App进行不安全的HTTP请求-->
                 <key>NSExceptionAllowsInsecureHTTPLoads</key>
                 <true/>
                 <!--在这里声明所支持的 TLS 最低版本-->
                 <key>NSExceptionMinimumTLSVersion</key>
                 <string>TLSv1.1</string>
             </dict>
         </dict>
     </dict>
 
 二、
 目前项目中用到的第三方已经支持https的有
 WKWebView
 UIWebView
 SDWebImage
 支付宝SDK
 微信支付SDK
 友盟SDK
 极光推送SDK
 
 其中用到的UIWebView 以后要逐步替换为WKWebView

转载于:https://my.oschina.net/jlongtian/blog/861790

iOS AFN
2016-02-29 14:21:36 tongwei117 阅读数 670
#define kActivityList @"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/activitylist.php"  // 活动列表 get

#define kNewsListURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"  // post请求
#define kNewsListParam @"date=20151102&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213" //body

#define kImageURL @"http://image.zcool.com.cn/56/13/1308200901454.jpg" // 图片, 下载用

#define kSearchURL @"http://api.map.baidu.com/place/v2/search?query=肯德基&region=北京&output=json&ak=6E823f587c95f0148c19993539b99295" // 带汉字的接口, 需要转码

post请求

// POST
- (void)post
{
    // 1.创建AFN管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    // 2.利用AFN管理者发送请求
    NSDictionary *params = @{
                             @"date" : @"20151102",
                             @"startRecord" : @"1",
                             @"len" : @"30",
                             @"udid" : @"1234567890",
                             @"terminalType" : @"Iphone",
                             @"cid" : @"213"
                             };
    // date=20151102&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213
    [manager POST:kNewsListURL parameters:params success:^
     (NSURLSessionDataTask *task, id responseObject) {
         NSLog(@"请求成功---%@", responseObject);
     } failure:^(NSURLSessionDataTask *task, NSError *error) {
         NSLog(@"请求失败---%@", error);
     }];
}

get请求

#pragma mark -- get请求
- (void)getjson
{
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    [manager GET:kActivityList parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//        NSLog(@"%@", responseObject);  // 这个接口的类型是 text/html
//    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
//        NSLog(@"-----%@", error);
//    }];
    NSString *string = [kSearchURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSLog(@"%@", string);
    NSURL *URL = [NSURL URLWithString:kActivityList];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager GET:URL.absoluteString parameters:nil success:^(NSURLSessionTask *task, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}

文件上传

#pragma mark -- 文件上传
- (void)upload
{
    // 1.创建网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 2.利用网络管理者上传数据
    NSDictionary *dict = @{@"username":@"Syl"};
    // formData: 专门用于拼接需要上传的数据
    [manager POST:@"http://120.25.226.186:32812/upload" parameters:dict
constructingBodyWithBlock:
     ^void(id<AFMultipartFormData> formData) {
         /*
          Data: 需要上传的数据
          name: 服务器参数的名称
          fileName: 文件名称
          mimeType: 文件的类型
          */
         UIImage *image =[UIImage imageNamed:@"hetu"];
         NSData *data = UIImagePNGRepresentation(image);
         [formData appendPartWithFileData:data name:@"file" fileName:@"hetu.png"
                                 mimeType:@"image/png"];
         /*
          NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/
          CertificateSigningRequest.certSigningRequest"];
          // 任意的二进制数据MIMEType application/octet-stream
          // [formData appendPartWithFileURL:url name:@"file" fileName:@"abc.cer"
          mimeType:@"application/octet-stream" error:nil];
          [formData appendPartWithFileURL:url name:@"file" error:nil];
          */
     } success:^void(NSURLSessionDataTask * task, id responseObject) {
         // 请求成功
         NSLog(@"请求成功 %@", responseObject);
     } failure:^void(NSURLSessionDataTask * task, NSError * error) {  
         // 请求失败  
         NSLog(@"请求失败 %@", error);  
     }];
}

文件下载

#pragma mark -- 文件下载
// 执行下载文件的方法,可以监控下载进度
- (void)downLoadMonitor
{
    // 1.创建网络管理者
    // AFHTTPSessionManager 基于NSURLSession
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   // NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    // 2.利用网络管理者下载数据
    // http://vss.waqu.com/dusdcsuang6u5btu/normal.mp4 视频的网址

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:kImageURL]];
    /*
     destination
     - targetPath: 系统给我们自动写入的文件路径
     - block的返回值, 要求返回一个URL, 返回的这个URL就是剪切的位置的路径
     completionHandler
     - url :destination返回的URL == block的返回的路径
     */
    /*
     @property int64_t totalUnitCount;  需要下载文件的总大小
     @property int64_t completedUnitCount; 当前已经下载的大小
     */
    NSProgress *progress = nil;
    NSURLSessionDownloadTask *downTask = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        // 缓存文件,如果想将缓存文件存到磁盘 SDURLCache
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:path];

    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"%@",filePath.absoluteString);
    }];

    /* 
     要跟踪进度,需要使用 NSProgress,是在 iOS 7.0 推出的,专门用来跟踪进度的类! 
     NSProgress只是一个对象!如何跟踪进度!-> KVO 对属性变化的监听! 
     @property int64_t totalUnitCount;        总单位数 
     @property int64_t completedUnitCount;    完成单位数 
     */  
    // 给Progress添加监听 KVO  
    [progress addObserver:self forKeyPath:@"completedUnitCount"   
                  options:NSKeyValueObservingOptionNew context:nil];  
    // 启动任务
    [downTask resume];  
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{

}
ios之AFN
2014-02-25 14:33:00 weixin_34175509 阅读数 0

https://github.com/AFNetworking/AFNetworking

与asi-http-request功能类似的网络库,不过是基于NSURLConnection 和 NSOperation 的,同样支持iOS与MacOS双平台。目前的更新比较频繁,适合新项目使用,而且使用起来也更简单。

操作JSON

复制代码
- (IBAction)jsonTapped:(id)sender {
    // 1
    NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
    NSURL *url = [NSURL URLWithString:weatherUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
 
    // 2
    AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:request
        // 3
        success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
            self.weather  = (NSDictionary *)JSON;
            self.title = @"JSON Retrieved";
            [self.tableView reloadData];
        }
        // 4
        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
            UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                         message:[NSString stringWithFormat:@"%@",error]
                                                        delegate:nil
                                               cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [av show];
        }];
 
    // 5
    [operation start];
}
复制代码
  1. 根据基本的URL构造出完整的一个URL。然后通过这个完整的URL获得一个NSURL对象,然后根据这个url获得一个NSURLRequest.
  2. AFJSONRequestOperation 是一个功能完整的类(all-in-one)— 整合了从网络中获取数据并对JSON进行解析。
  3. 当请求成功,则运行成功块(success block)。在本示例中,把解析出来的天气数据从JSON变量转换为一个字典(dictionary),并将其存储在属性 weather 中.
  4. 如果运行出问题了,则运行失败块(failure block),比如网络不可用。如果failure block被调用了,将会通过提示框显示出错误信息。

 

操作Property Lists(plists)

复制代码
 -(IBAction)plistTapped:(id)sender{
    NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=plist",BaseURLString];
    NSURL *url = [NSURL URLWithString:weatherUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
 
    AFPropertyListRequestOperation *operation =
    [AFPropertyListRequestOperation propertyListRequestOperationWithRequest:request
        success:^(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList) {
            self.weather  = (NSDictionary *)propertyList;
            self.title = @"PLIST Retrieved";
            [self.tableView reloadData];
        }
        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList) {
            UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                              message:[NSString stringWithFormat:@"%@",error]
                                                        delegate:nil
                                               cancelButtonTitle:@"OK"
                                               otherButtonTitles:nil];
            [av show];
    }];
 
    [operation start];
}
复制代码

上面的代码几乎与JSON版的一致,只不过将操作(operation)的类型从AFJSONOperation 修改为 AFPropertyListOperation.

操作XML

复制代码
- (IBAction)xmlTapped:(id)sender{
    NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=xml",BaseURLString];
    NSURL *url = [NSURL URLWithString:weatherUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
 
    AFXMLRequestOperation *operation =
    [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request
        success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
            //self.xmlWeather = [NSMutableDictionary dictionary];
            XMLParser.delegate = self;
            [XMLParser setShouldProcessNamespaces:YES];
            [XMLParser parse];
        }
        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {
            UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                         message:[NSString stringWithFormat:@"%@",error]
                                                        delegate:nil
                                               cancelButtonTitle:@"OK"
                                               otherButtonTitles:nil];
            [av show];
    }];
 
    [operation start];
}
复制代码

到现在为止,这看起来跟之前处理JSON和plist很类似。最大的改动就是在成功块(success block)中, 在这里不会传递给你一个预处理好的NSDictionary对象. 而是AFXMLRequestOperation实例化的NSXMLParse对象,这个对象将用来处理繁重的XML解析任务。

NSXMLParse对象有一组delegate方法是你需要实现的 — 用来获得XML数据。注意,在上面的代码中我将XMLParser的delegate设置为self, 因此WTTableViewController将用来处理XML的解析任务。

下载图片

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
复制代码
- (IBAction)updateBackgroundImage:(id)sender {
 
    //Store this image on the same server as the weather canned files
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.scott-sherwood.com/wp-content/uploads/2013/01/scene.png"]];
    AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request
        imageProcessingBlock:nil
        success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
            self.backgroundImageView.image = image;
            [self saveImage:image withFilename:@"background.png"];
        }
        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
            NSLog(@"Error %@",error);
    }];
    [operation start];
}
复制代码
复制代码
-(void)saveImage:(UIImage *)image withFilename:(NSString *)filename{
    
    NSString *path;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"WeatherHTTPClientImages/"];
    
    
    BOOL isDir;
    
    if(![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]){
        if(!isDir){
            NSError *error;
            [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
            
            NSLog(@"%@",error);
        }
    }
    
    path = [path stringByAppendingPathComponent:filename];
    NSData *imageData = UIImagePNGRepresentation(image);
    NSLog(@"Written: %d",[imageData writeToFile:path atomically:YES]);
}
复制代码

 

AFHTTPClient

AFHTTPClient一般是给它设置一个基本的URL,然后用AFHTTPClient进行多个请求(而不是像之前的那样,每次请求的时候,都创建一个AFHTTPClient)。

复制代码
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(buttonIndex==0){
        NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:BaseURLString]];
        NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"json" forKey:@"format"];
        
        AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
        [client registerHTTPOperationClass:[AFJSONRequestOperation class]];
        [client setDefaultHeader:@"Accept" value:@"application/json"];
        
        [client postPath:@"weather.php"
              parameters:parameters
                 success:^(AFHTTPRequestOperation *operation, id responseObject) {
                     self.weather = responseObject;
                     self.title = @"HTTP POST";
                     [self.tableView reloadData];
                 }
                 failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                     UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                                  message:[NSString stringWithFormat:@"%@",error]
                                                                 delegate:nil
                                                        cancelButtonTitle:@"OK" otherButtonTitles:nil];
                     [av show];
                     
                 }
         ];
    }
    else if (buttonIndex==1){
        NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:BaseURLString]];
        NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"json" forKey:@"format"];
        
        AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
        [client registerHTTPOperationClass:[AFJSONRequestOperation class]];
        [client setDefaultHeader:@"Accept" value:@"application/json"];
        
        [client getPath:@"weather.php"
             parameters:parameters
                success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    self.weather = responseObject;
                    self.title = @"HTTP GET";
                    [self.tableView reloadData];
                }
                failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                                 message:[NSString stringWithFormat:@"%@",error]
                                                                delegate:nil
                                                       cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [av show];
                    
                }
         ];
    }
}
复制代码
  1. 构建一个baseURL,以及一个参数字典,并将这两个变量传给AFHTTPClient.
  2. 将AFJSONRequestOperation注册为HTTP的操作, 这样就可以跟之前的示例一样,可以获得解析好的JSON数据。
  3. 做了一个GET请求,这个请求有一对block:success和failure。
  4. POST请求跟GET一样。

 

上传一个文件

复制代码
NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
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/jpeg"];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];
复制代码

下载一个文件

复制代码
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]];
operation.outputStream = [NSOutputStream outputStreamToMemory];
[operation start];
复制代码

 

参考:

http://www.raywenderlich.com/zh-hans/36079/afnetworking%E9%80%9F%E6%88%90%E6%95%99%E7%A8%8B%EF%BC%881%EF%BC%89

转载于:https://www.cnblogs.com/yulang314/p/3566668.html

2015-09-30 11:22:55 iotjin 阅读数 321

问题:

在AFSecurityPolicy.m这个类中,会报这样三个错误

  1. Use of undeclared identifier 'kSecFormatUnknown'

  2. Use of undeclared identifier 'kSecItemPemArmour'

  3. Implicit declaration of function 'SecItemExport' is invalid in C99

在.pch文件中加入如下代码即可:

#ifndef TARGET_OS_IOS


#define TARGET_OS_IOS TARGET_OS_IPHONE


#endif


#ifndef TARGET_OS_WATCH


#define TARGET_OS_WATCH 0


#endif

ios之AFN

阅读数 2

iOS - ASI与AFN

阅读数 546

iOS - 网路-AFN

阅读数 9

没有更多推荐了,返回首页