码迷,mamicode.com
首页 > 移动开发 > 详细

iOS AFN

时间:2015-11-19 01:47:34      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:

AFN

NSURLConnection包装方法

  • GET

  • // 1.创建AFN管理者
    // AFHTTPRequestOperationManager内部包装了NSURLConnection
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    // 2.利用AFN管理者发送请求
    NSDictionary *params = @{
                           @"username" : @"name",
                           @"pwd" : @"password"
                           };
    [manager GET:@"http://12.2.226.186:32812/login" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
       NSLog(@"请求成功---%@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       NSLog(@"请求失败---%@", error);
    }];

     

  • POST
  • // 1.创建AFN管理者
    // AFHTTPRequestOperationManager内部包装了NSURLConnection
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    // 2.利用AFN管理者发送请求
    NSDictionary *params = @{
                           @"username" : @"name",
                           @"pwd" : @"password"
                           };
    [manager POST:@"http://12.2.226.186:32812/login" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
      NSLog(@"请求成功---%@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      NSLog(@"请求失败---%@", error);
    }];

     

NSURLSession包装方法

  • GET

    // 1.创建AFN管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2.利用AFN管理者发送请求
    NSDictionary *params = @{
                           @"username" : @"name",
                           @"pwd" : @"password"
                           };
    
    [manager GET:@"http://12.2.226.186:32812/login" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
       NSLog(@"请求成功---%@", responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
      NSLog(@"请求失败---%@", error);
    }];

     

  • POST
  • // 1.创建AFN管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2.利用AFN管理者发送请求
    NSDictionary *params = @{
                           @"username" : @"name",
                           @"pwd" : @"password"
                           };
    
    [manager POST:@"http://12.2.226.186:32812/login" parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
      NSLog(@"请求成功---%@", responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
      NSLog(@"请求失败---%@", error);
    }];

     

文件下载

 // 1.创建AFN管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    // 2.利用AFN管理者发送请求
     NSURLRequest *reuqest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://12.2.226.186:32812/resources/videos/minion_02.mp4"]];

    [[manager downloadTaskWithRequest:reuqest progress:nil  destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        // targetPath: 已经下载好的文件路径
        NSLog(@"targetPath = %@", targetPath);
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[path stringByAppendingPathComponent:response.suggestedFilename]];
        // 返回需要保存文件的目标路径
        return documentsDirectoryPath;
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"filePath = %@", filePath);
    }] resume];

 

 

监听进度

/*
     要跟踪进度,需要使用 NSProgress,是在 iOS 7.0 推出的,专门用来跟踪进度的类!

     NSProgress只是一个对象!如何跟踪进度!-> KVO 对属性变化的监听!
     @property int64_t totalUnitCount;        总单位数
     @property int64_t completedUnitCount;    完成单位数
     */
    NSProgress *progress = nil;
    // 注册通知
    [progress addObserver:self forKeyPath:@"completedUnitCount" options:NSKeyValueObservingOptionNew context:nil];
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSLog(@"%@", object);
    /**
     准确的获得进度
     localizedDescription               10%
     localizedAdditionalDescription     completed 32,768 of 318,829
     fractionCompleted                  0.102776(completedUnitCount/totalUnitCount)
     */
    if ([object isKindOfClass:[NSProgress class]]) {
        NSProgress *p = (NSProgress *)object;
        NSLog(@"%@, %@, %f", p.localizedDescription, p.localizedAdditionalDescription, p.fractionCompleted);

文件上传

// 1.创建AFN管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    // 2.利用AFN管理者发送请求
    [manager POST:@"http://12.2.226.186:32812/upload" parameters:@{@"username" : @"jx"} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSData *data = [NSData dataWithContentsOfFile:@"/Users/Jx-Liu/Desktop/Snip20150811_1.png"];
        [formData appendPartWithFileData:data name:@"file" fileName:@"jx.png" mimeType:@"image/png"];
    } success:^(NSURLSessionDataTask *task, id responseObject) {
          NSLog(@"请求成功---%@", responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"请求失败---%@", error);
    }];
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/Jx-Liu/Desktop/Snip20150811_1.png"] name:@"file" fileName:@"jx.png" mimeType:@"image/png" error:nil];
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/Jx-Liu/Desktop/Snip20150811_1.png"] name:@"file" error:nil];
  • AFN解耦

    • 自定义单利类基础Manager
    • 优点: 替换框架只需要求改单利类即可
  • 序列化

    • AFN默认将服务器返回的数据当做JSON处理, 会自动解析
      • manager.responseSerializer = [AFJSONRequestSerializer serializer];
    • 告诉AFN,以XML形式解析服务器返回的数据
      • manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
    • 告诉AFN, 不处理服务器返回的数据, 原样返回
      • manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  • 网络状态检测
  • / 1.创建网络监听对象
        AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
        // 2.设置网络状态改变回调
        [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            /*
             AFNetworkReachabilityStatusUnknown          = -1,  // 未知
             AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接
             AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G 花钱
             AFNetworkReachabilityStatusReachableViaWiFi = 2,   // 局域网络,不花钱
             */
            switch (status) {
                case 0:
                    NSLog(@"无连接");
                    break;
                case 1:
                    NSLog(@"3G 花钱");
                    break;
                case 2:
                    NSLog(@"局域网络,不花钱");
                    break;
                default:
                    NSLog(@"未知");
                    break;
            }
        }];
    
        // 3.开始监听
        [manager startMonitoring];
  • 苹果自带
  •     - (void)viewDidLoad {
        [super viewDidLoad];
    
        // 注册通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNetworkStatus) name:kReachabilityChangedNotification object:nil];
    
        // 开始监听网络
        self.reachability = [Reachability reachabilityForInternetConnection];
        [self.reachability startNotifier];
    }
    
    - (void)dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [self.reachability stopNotifier];
    }
    - (void)getNetworkStatus{
        if ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus != NotReachable) {
            NSLog(@"wifi");
        }else if ([Reachability reachabilityForInternetConnection].currentReachabilityStatus != NotReachable)
        {
            NSLog(@"手机自带网络");
        }else
        {
            NSLog(@"没有网络");
        }
    }

    CocoaPods安装失败

    • CocoaPods安装东西的时候它要找到Xcode的Developer文件夹, 如果找不到会报如下错误

    • 技术分享
    • 解决方案

      • JX替换为你自己的用户名
      • sudo xcode-select --switch /Users/JX/Applications/Xcode.app/Contents/Developer

        技术分享

      • 技术分享

iOS AFN

标签:

原文地址:http://www.cnblogs.com/liujiaoxian/p/4976399.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!