AFNetworking
NSURLConnection
---导入头文件"AFHTTPRequestOperationManager.h"
1. 发送GET请求
//发送get请求
- (void)get {
[[AFHTTPRequestOperationManager manager] GET:@"http://127.0.0.1/demo.json" parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"%@",responseObject);
NSLog(@"%@",[responseObject class]);
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
}
2. 发送GET请求--带参数
//发送get请求,传参数
- (void)get {
[[AFHTTPRequestOperationManager manager] GET:@"http://127.0.0.1/php/login.php" parameters:@{@"username":@"abc",@"password":@"123"} success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
}
3. 发送POST请求
//演示post请求
- (void)post {
[[AFHTTPRequestOperationManager manager] POST:@"http://127.0.0.1/php/login.php" parameters:@{@"username":@"abcd",@"password":@"lalala"} success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
}
4. 上传文件
- (void)post {
//获取要上传文件的路径
NSURL *url1 = [[NSBundle mainBundle] URLForResource:@"06.jpg" withExtension:nil];
NSURL *url2 = [[NSBundle mainBundle] URLForResource:@"01.jpg" withExtension:nil];
[[AFHTTPRequestOperationManager manager] POST:@"http://127.0.0.1/php/upload/upload-m.php" parameters:@{@"username":@"zhangsan"} constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
//上传文件
[formData appendPartWithFileURL:url1 name:@"userfile[]" error:nil];
[formData appendPartWithFileURL:url2 name:@"userfile[]" error:nil];
} success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"%@",responseObject);
} failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
}
NSURLSession
---导入头文件"AFHTTPSessionManager.h"
1. 发送GET请求
- (void)get {
[[AFHTTPSessionManager manager] GET:@"http://127.0.0.1/demo.json" parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
NSLog(@"%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
}
2. 下载任务
- (void)download {
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/abc.hm"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//进度
NSProgress *progress = nil;
[[[AFHTTPSessionManager manager] downloadTaskWithRequest:request progress:&progress destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
// NSLog(@"targetPath -- %@",targetPath);
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
// 本地文件的URL必须使用这种方式获取
NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
//返回要保存文件的路径
return url;
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
NSLog(@"%@",filePath);
}] resume];
//观察progress的某个属性fractionCompleted(进度)是否发生变化
//KVO
[progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
if ([object isKindOfClass:[NSProgress class]]) {
// NSLog(@"%@",change);
NSProgress *progress = object;
NSLog(@"%@",progress.localizedDescription);
NSLog(@"%@",progress.localizedAdditionalDescription);
NSLog(@"completedUnitCount : %zd",progress.completedUnitCount);
NSLog(@"totalUnitCount : %zd",progress.totalUnitCount);
NSLog(@"fractionCompleted : %f",progress.fractionCompleted);
//回到主线程更新UI
NSLog(@"%@",[NSThread currentThread]);
}
}
3. 获取网页数据--修改默认的序列化器
- (void)getBaidu {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//修改响应的序列化器
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"http://www.baidu.com" parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
NSString *html = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@",html);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
}
4. 解析XML
- (void)getXML {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 设置序列号器为XML,也可修改为AFHTTPResponseSerializer,使用第三方框架解析二进制数据
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
[manager GET:@"http://127.0.0.1/videos.xml" parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, NSXMLParser *responseObject) {
//解析xml
responseObject.delegate = self;
[responseObject parse];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
}
//NSXMLParser 的代理方法
- (void)parserDidStartDocument:(NSXMLParser *)parser {
NSLog(@"1 开始解析");
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict {
NSLog(@"2 开始节点 %@ %@",elementName,attributeDict);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
NSLog(@"3 节点之间的内容 %@",string);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
NSLog(@"4 结束节点 %@",elementName);
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSLog(@"5 结束解析");
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSLog(@"6 错误");
}