iOS项目框架搭建

iOSAFNetworking

2016-12-20  本文已影响21人  哔哩哔哩智能喵
#import "ViewController.h"
#import "AFNetworking.h"
@interface ViewController ()
@end

@implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self sendGet];
}
-(void)sendPost
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // http://120.25.226.186:32812/login?username=123&pwd=122&type=JSON
    
    NSDictionary *dict  = @{
                            @"username":@"520it",
                            @"pwd":@"520it",
                            @"type":@"JSON"
                            };
    //2.发送GET请求
    /*
     第一个参数:请求路径(不包含参数).NSString
     第二个参数:字典(发送给服务器的数据-参数)
     第三个参数:progress 进度回调
     第四个参数:success 成功回调
     task:请求任务
     responseObject:响应体信息(JSON--->OC对象)
     第五个参数:failure 失败回调
     error:错误信息
     响应头:task.response
     */
    [manager POST:@"http://120.25.226.186:32812/login" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@---%@------",[responseObject class],responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error  =%@",error);
    }];
}
-(void)sendGet
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *dict  = @{
                            @"username":@"520it",
                            @"pwd":@"520it",
                            @"type":@"JSON"
                            };
    [manager GET:@"http://120.25.226.186:32812/login" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject = %@---%@------",[responseObject class],responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error = %@",error);
    }];
}
@end
-(void)download
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    /**
     第一个参数:请求对象
     第二个参数:progress 进度回调 downloadProgress
     第三个参数:destination 回调(目标位置)
                有返回值
                targetPath 临时文件路径
                response 响应头信息
     第四个参数:completionHandler 下载完成之后的回调
                filePath        最终的文件路径
     */
    NSURLSessionDownloadTask *downloadTask  = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
       /**
        *  监听下载进度
           completedUnitCount 已经下载的数据大小
           totalUnitCount     文件数据的总大小
        */
        NSLog(@"---%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:response.suggestedFilename];
        
        NSLog(@"targetPath:%@",targetPath);
        
        NSLog(@"fullPath:%@",fullPath);
        return  [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"%@",filePath);
    }];
    
    [downloadTask resume];
}

-(void)upload
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"http://120.25.226.186:32812/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        UIImage *image = [UIImage imageNamed:@"Snip20160227_128"];
        NSData *imageData = UIImagePNGRepresentation(image);
        /*
         第一个参数:二进制数据 要上传的文件参数
         第二个参数:服务器规定的
         第三个参数:该文件上传到服务器以什么名称保存
         第四个参数:图片的MIME类型
         */
//        [formData appendPartWithFileData:imageData name:@"imageData" fileName:@"111.png" mimeType:@"image/png"];
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/yao/Desktop/Snip20160227_128.png"] name:@"file" error:nil];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"----%f", 1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"上传成功---%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传失败---%@",error);
    }];
}
#import "ViewController.h"
#import "AFNetworking.h"
@interface ViewController ()<NSXMLParserDelegate>

@end

@implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self httpData2];
}
-(void)XML
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //修改AFN的解析方案,默认为JSON
    manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
    NSDictionary *paramDict = @{
                                @"type":@"XML"
                                };
    [manager GET:@"http://120.25.226.186:32812/video" parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSXMLParser *parser =(NSXMLParser *)responseObject;
        
        //设置代理
        parser.delegate = self;
        
        //开始解析
        [parser parse];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error = %@",error);
    }];
}
#pragma mark NSXMLParserDelegate
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict
{
    NSLog(@"%@--%@",elementName,attributeDict);
}
-(void)httpData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    /**
     *  如果返回的既不是XML也不是JSON可以修改解析方案为AFN自带解析方案
     */
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:@"http://120.25.226.186:32812/resources/images/minion_01.png" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task,id  _Nullable responseObject) {
        NSLog(@"%@-",[responseObject class]);
        
        //UIImage *image = [UIImage imageWithData:responseObject];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败--%@",error);
    }];
}
-(void)httpData2
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    /**
     *  AFN内部只能接受@"application/json", @"text/json", @"text/javascript"这三种默认类型的数据,需要再加一组
     */
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:@"http://www.baidu.com" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@-%@",[responseObject class],[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error = %@",error);
    }];
}
@end


    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    //监听状态的改变
    /*
     AFNetworkReachabilityStatusUnknown          = -1, 未知
     AFNetworkReachabilityStatusNotReachable     = 0,  没有网络
     AFNetworkReachabilityStatusReachableViaWWAN = 1,  蜂窝网络
     AFNetworkReachabilityStatusReachableViaWiFi = 2   Wifi
     */
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"蜂窝网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WIFI");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络");
                break;
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知");
                break;
            default:
                break;
        }
    }];
    
    //开始监听
    [manager startMonitoring];
上一篇下一篇

猜你喜欢

热点阅读