一 AFNetWorking
目前非常受欢迎的网络开源库,它拥有良好的架构,丰富的API,以及模块化的构建方式,使用起来非常简洁轻松;
AFNetWorking新版本不仅封装了NSURLConnection,还封装了NSURLSession等相关功能,可以让程序员简单的操作就可以轻松的实现GET/POST请求数据,下载文件,上传文件/上传图片,检测网络状态等相关功能,还非常贴心的帮助程序员直接处理一些JSON/XML格式的解析;
1.1 检测网络状态和GET请求,POST,文件下载
【Demo】-【1-AFNetWorking_GET】
//检测是否有网络,有什么网络?
-
(IBAction)netinfo:(id)sender {
//1.获取网络监控的管理者
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];//2.设置网络方式变化时的代码
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {switch (status) { case AFNetworkReachabilityStatusUnknown: NSLog(@"未知网络"); break; case AFNetworkReachabilityStatusNotReachable: NSLog(@"无网络"); break; case AFNetworkReachabilityStatusReachableViaWiFi: NSLog(@"WIFI"); break; case AFNetworkReachabilityStatusReachableViaWWAN: NSLog(@"手机自己的网络(3G/4G)"); break; default: break; }
}];
//3.启动监控
[manager startMonitoring];
//4.判断是什么网络?(返回的是bool值)
[manager isReachableViaWiFi];//WIFI
[manager isReachableViaWWAN];//蜂窝网络
[manager isReachable];//YES 有网 NO没有网络
}
//get请求数据
-
(IBAction)getRequestData:(id)sender {
//1.获得请求对象
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//2.设置返回的数据格式
//直接返回的是NSData类型 [AFHTTPResponseSerializer serializer]
//返回的是JSON格式 [AFJSONResponseSerializer serializer];
//返回的是XML格式 [AFXMLParserResponseSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];//3.发起GET请求
[manager GET:@"http://mapi.damai.cn/proj/HotProj.aspx?CityId=0&source=10099&version=30602" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {//请求成功 NSLog(@"请求成功"); NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]; NSLog(@"%@",dict);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"请求失败");
}];
}
//POST请求
-
(IBAction)postRequestData:(id)sender {
NSString *urlStr = @"http://10.0.8.8/sns/my/user_list.php";
//拼接请求体的内容【这里拼接成字典,数组,字符串】
NSDictionary *bodyDict = @{@"page":@2,@"number":@10};
NSArray *bodyArr = @[@"page",@3,@"number",@10];
NSString *bodyStr = @"page=2,number=10";//1.创建网络请求对象
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];//2.设置响应格式
manager.responseSerializer = [AFHTTPResponseSerializer serializer];//3.POST请求
[manager POST:urlStr parameters:bodyDict success:^(AFHTTPRequestOperation *operation, id responseObject) {NSLog(@"请求成功"); NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]; NSLog(@"%@",dict);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"请求失败");
}];
}
//文件下载
-
(IBAction)downLoadFile:(id)sender {
NSString *urlStr = @"http://10.6.154.91/share/音乐/好难得.mp3";
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//1.构造NSURL
NSURL *url = [NSURL URLWithString:urlStr];//2.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];//3.创建AFURLSessionManager对象
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];//4.创建任务
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {//下载成功后,返回最终将要把tmp文件保存的文件存储到哪个目录所对应的路径 NSString *toPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/好难得.mp3"]; NSLog(@"%@",toPath); NSURL *url = [NSURL fileURLWithPath:toPath]; return url;
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//不管成功,还是失败都会调用该代码块
//filePath代表的是下载的文件所在的路径
//error错误信息,如果为NULL,表示下载成功
NSLog(@"下载失败:%@",error);}];
//5.启动任务
[task resume];
} -
(void)viewDidLoad {
[super viewDidLoad];[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}
1.2 进度条监听文件下载的进度
【Demo】-【2-AFNetWorking_progress】
-
(IBAction)downLoadFile:(id)sender {
NSString *urlStr = @"http://10.6.154.91/share/视频/1.mp4";
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//1.构造NSURL对象
NSURL *url = [NSURL URLWithString:urlStr];//2.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];//3.创建AFURLSessionManager对象
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];//4.创建下载任务
//第二个参数是进度对象指针的地址,为了返回进度
NSProgress *progress = nil;
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {//返回最终文件所对应的目录 NSString *toPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/1.mp4"]; return [NSURL fileURLWithPath:toPath];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"%@ error:%@",filePath.path,error);
}];
//5.启动任务
[task resume];//得到progress对象,需要使用成员变量保存起来
//用成员变量指向,做了一个强引用,保证刚刚创建的progress对象不会在当前方法结束时消失
self.myProgress = progress;//使用kvc/kvo的设计模式,来观察进度
//让self做为观察者来观察self.myProgress的属性,fractionCompleted(表示完成的进度)
[self.myProgress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];
}
//观察者调用的方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (object == self.myProgress && [keyPath isEqualToString:@"fractionCompleted"]) {
//回到主线程,更新进度条的显示
dispatch_async(dispatch_get_main_queue(), ^{
[self.myProgressView setProgress:self.myProgress.fractionCompleted animated:YES];
NSLog(@"%.2lf",self.myProgress.fractionCompleted);
});
}
}
二 图片选取器 UIImagePickerController
见【Demo】-【3-UIImagePickerController】
-
(IBAction)changeImage:(id)sender {
//创建图片选取器对象
UIImagePickerController *pickVC = [[UIImagePickerController alloc] init];pickVC.delegate = self;
[self presentViewController:pickVC animated:YES completion:nil];
}
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
pragma mark -图片选取器对应的代理方法
//1.当我们选中相册中的某张图片,调用
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSLog(@"选中了某张图片");
//获得选中图片所对应的原图
UIImage *image = info[@"UIImagePickerControllerOriginalImage"];//打印info,找到图片对应的key值
self.myImageView.image = image;
// NSLog(@"%@",info);
[self dismissViewControllerAnimated:YES completion:nil];
}
//2.当我们点击cancle调用
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
NSLog(@"cancel");
//直接返回
[self dismissViewControllerAnimated:YES completion:nil];
}
关于状态栏样式的设置:
1.在info.plist文件添加属性View controller-based status bar appearance 值设置no
2.在代码部分设置
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;