1.监控网络状态
// 1.获得网络监控的管理者
AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
// 2.设置网络状态改变后的处理
[mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
// 当网络状态改变了, 就会调用这个block
switch (status) {
case AFNetworkReachabilityStatusUnknown: // 未知网络
[self setupRefresh];
break;
case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
[SVProgressHUD showImage:nil status:@"请连接网络"];
[self getStatusFromCache];
break;
case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
[self setupRefresh];
break;
case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
[self setupRefresh];
break;
}
}];
// 3.开始监控
[mgr startMonitoring];
2.发送POST请求
// 请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
TWAccount *accout = [TWAccountTool account];
params[@"key"] = accout.key;
params[@"client"] = @"ios";
[[AFHTTPSessionManager manager] POST:@"http://www.jixuejiyong.com/mobile/index.php?act=hg_member_sns_home&op=friends_circle" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
TTLog(@"%@",responseObject);
self.topics = [TWMyStatus mj_objectArrayWithKeyValuesArray:responseObject[@"datas"][@"tracelist"]];
// 缓存
[TWStatusCacheTool addStatuses:_topics];
//------------所有界面UI刷新都要放在主线程里面刷新-----------
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
//-----------------------------------------------------
[self.tableView.mj_header endRefreshing];
[SVProgressHUD dismiss];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[self.tableView.mj_header endRefreshing];
[SVProgressHUD showErrorWithStatus:@"请求错误"];
}];
}
3.发送GET请求
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"type"] = @1;
params[@"phone"] = self.phone;
params[@"captcha"] = self.param1[@"datas"][@"captcha"];
params[@"nchash"] = self.param1[@"datas"][@"nchash"];
[[AFHTTPSessionManager manager] GET:@"http://www.jixuejiyong.com/mobile/index.php?act=hg_member_sns_home&op=get_captcha" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (![responseObject[@"datas"][@"result"] isEqualToString:@"ture"]) {
[SVProgressHUD showErrorWithStatus:@"发送短信失败"];
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[SVProgressHUD showErrorWithStatus:@"发送短信失败"];
}];
4.上传图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// 获取选中的图片
UIImage *image = info[@"UIImagePickerControllerEditedImage"];
// 对图片做裁剪
self.imgView.image = [ImageTool image:image byScalingToSize:CGSizeMake(120, 120)];
// 对裁剪过的图片做本地化存储
NSString *patch = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSData *imageData = UIImagePNGRepresentation(self.imgView.image);
[imageData writeToFile:[NSString stringWithFormat:@"%@/%@",patch,@"icon.png"] atomically:YES];
// 请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
TWAccount *accout = [TWAccountTool account];
params[@"key"] = accout.key;
params[@"client"] = @"ios";
// 上传头像
[[AFHTTPSessionManager manager] POST:@"http://www.jixuejiyong.com/mobile/index.php?act=hg_member_sns_home&op=changeAvatarHandle" parameters:params constructingBodyWithBlock:^(id _Nonnull formData) {
[formData appendPartWithFileData:imageData name:@"file" fileName:@"icon.png" mimeType:@"image/png"];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
TWAccount *accout = [TWAccountTool account];
accout.member_avatar = responseObject[@"datas"][@"result"][@"src"];
[TWAccountTool saveAccount:accout];
TTLog(@"哈哈%@",responseObject[@"datas"][@"result"][@"src"]);
if ([responseObject[@"datas"][@"src"] isEqualToString:@""]) {
[SVProgressHUD showErrorWithStatus:@"操作失败"];
}else{
// 请求参数
NSMutableDictionary *params1 = [NSMutableDictionary dictionary];
params1[@"key"] = accout.key;
params1[@"client"] = @"ios";
params1[@"id"] = accout.member_id;
params1[@"src"] = responseObject[@"datas"][@"result"][@"src"];
// 修改头像
[[AFHTTPSessionManager manager] POST:@"http://www.jixuejiyong.com/mobile/index.php?act=hg_member_sns_home&op=avatarheader" parameters:params1 progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if ([responseObject[@"datas"][@"result"] isEqualToString:@"success"]) {
[SVProgressHUD showImage:nil status:@"修改成功"];
}else{
[SVProgressHUD showErrorWithStatus:@"操作失败"];
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[SVProgressHUD showErrorWithStatus:@"请求错误"];
}];
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[SVProgressHUD showErrorWithStatus:@"请求错误"];
}];
[picker dismissViewControllerAnimated:YES completion:nil];
}
5.AFHTTPSessionManager内部包装了NSURLSession
AFHTTPRequestOperationManager内部包装了NSURLConnection
这两者都可以发送网络请求。
6.下载
- (void)download
{
// AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
//
// [mgr downloadTaskWithRequest:<#(NSURLRequest *)#> progress:<#(NSProgress *__autoreleasing *)#> destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
// return
// } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//
// }];
}
7.上传图片的另一种做法(无参数)
- (void)upload2
{
// AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
// [mgr uploadTaskWithRequest:<#(NSURLRequest *)#> fromData:<#(NSData *)#> progress:<#(NSProgress *__autoreleasing *)#> completionHandler:<#^(NSURLResponse *response, id responseObject, NSError *error)completionHandler#>];
}
8.解析xml的数据
- (void)xml
{
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
// responseSerializer 用来解析服务器返回的数据
// 告诉AFN,以XML形式解析服务器返回的数据
mgr.responseSerializer = [AFXMLParserResponseSerializer serializer];
NSDictionary *params = @{
@"username" : @"520it",
@"pwd" : @"520it",
@"type" : @"XML"
};
[mgr GET:@"http://120.25.226.186:32812/login" parameters:params success:^(NSURLSessionDataTask *task, NSXMLParser *parser) {
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"请求失败---%@", error);
}];
}
9.解析返回数据
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
// 直接使用“服务器本来返回的数据”,不做任何解析
mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
// [AFJSONResponseSerializer serializer]; // 解析服务器返回的JSON数据
// [AFXMLParserResponseSerializer serializer]; // 解析服务器返回的XML数据