-(void)reach
{
/**
AFNetworkReachabilityStatusUnknow = -1,//未知
AFNetworkReachabilityStatusNotReachable = 0, //无连接
AFNetworkReachabilityStatusReachableViaWWAN = 1, // 3G,花钱
AFNetworkReachabilityStatusReachableViaWiFi = 2, //WiFi
*/
//如果要检测网络状态的变化,必须要用检测管理者的单利startMonitoring
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
//检测网络连接的单利,网络变化时回调方法
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"---%ld",status);
}];
}
-(void)sessionDownload
{
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//基于NSUrlSessionManager的(iOS7+。Mac OS 10.9+,以前的版本用AFHTTPRequestOpreationManager)
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:config];
NSString *urlString = FILE_REMOTE_URL;
urlString=[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlString];
NSLog(@"urlString=%@",urlString);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSLog(@"request=%@",request);
//创建一个下载任务
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
//指定下载文件保存的路径
NSLog(@"target=%@-suggest=%@",targetPath,response.suggestedFilename);
//将下载文件保存在Document路径中
NSString *FileDoc =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *path = [FileDoc stringByAppendingPathComponent:response.suggestedFilename];
//URLWithString返回的是网络的URL,如果使用本地URL,需要注意
NSURL *fileUrl1 = [NSURL URLWithString:path];
NSURL *fileUrl = [NSURL fileURLWithPath:path];
NSLog(@"fileUrl1-%@,fileUrl-%@",fileUrl1,fileUrl);
return fileUrl;
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//下载完成的方法
NSLog(@"filePath=%@,errer=%@",filePath,error);
NSData *data=[NSData dataWithContentsOfURL:filePath];
UIImage *image=[UIImage imageWithData:data];
UIImageView *imageView=[[UIImageView alloc]initWithImage:image];
imageView.backgroundColor=[UIColor redColor];
imageView.frame=CGRectMake(10, 20, 140, 200);
[self.view addSubview:imageView];
}];
[task resume];//开始任务
}
/**
* AFN原来的下载文件方法,现在仍然可以用
*
* @param string aUrl 请求文件地址
* @param string aFilePath 保存地址
* @param string aFileName 文件名
* @param int aTag标识
*/
-(void)downFileWithUrl:(NSString *)aUrl savePath:(NSString *)aFilePath fileName:(NSString *)aFileName tag:(NSInteger)aTag
{
NSLog(@"-%@-%@-%@",aUrl,aFilePath,aFileName);
NSFileManager *manager=[NSFileManager defaultManager];
//检查本地文件是否存在
NSString *fileName=[NSString stringWithFormat:@"%@/%@",aFilePath,aFileName];
//文件已经存在直接读取
NSLog(@"file=%@",fileName);
if ([manager fileExistsAtPath:fileName])//
{
UIImage *image=[UIImage imageWithContentsOfFile:fileName];
UIImageView *imageView=[[UIImageView alloc]initWithImage:image];
imageView.frame=CGRectMake(170, 20, 140, 200);
[self.view addSubview:imageView];
} else {
//如果没有就创建文件路径
//先创建文件的存放的文件夹路径
if(![manager fileExistsAtPath:aFileName])
{
//创建文件存放的路径
[manager createDirectoryAtPath:aFileName withIntermediateDirectories:YES attributes:nil error:nil];
}
//下载文件
NSURL *url=[NSURL URLWithString:aUrl];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *opration=[[AFHTTPRequestOperation alloc] initWithRequest:request];
//设置从哪里下载
opration.inputStream=[NSInputStream inputStreamWithURL:url];
//设置下载完了放在那里
opration.outputStream=[NSOutputStream outputStreamToFileAtPath:fileName append:NO];
//设置下载进度
[opration setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
NSLog(@"----%f",(float)totalBytesRead/totalBytesExpectedToRead);
}];
//已完成下载
[opration setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//显示图片
UIImage *image=[UIImage imageWithContentsOfFile:fileName];
UIImageView *imageView=[[UIImageView alloc]initWithImage:image];
imageView.frame=CGRectMake(170, 20, 140, 200);
[self.view addSubview:imageView];
NSLog(@"fileName=%@",fileName);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"下载失败!=%@",error);
}];
[opration start];
}
}
-(void)jsonRequest
{
//创建一个请求队列管理者
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes=nil;
//GET只接受JSON
[manager GET:JSON_DIC_URL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
UITextView *textView=[[UITextView alloc]initWithFrame:CGRectMake(10, 230, 140, 200)];
[self.view addSubview:textView];
textView.scrollEnabled = YES;
textView.text=[NSString stringWithFormat:@"%@:%@",[responseObject class],responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"请求失败:%@",error);
}];
}
-(void)XMLRequest
{
//请求过程
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:XML_DIC_URL]];
AFHTTPRequestOperation *Operation=[[AFHTTPRequestOperation alloc]initWithRequest:request];
//添加XML的解析器
Operation.responseSerializer=[AFXMLParserResponseSerializer serializer];
UITextView *textView=[[UITextView alloc]initWithFrame:CGRectMake(170, 230, 140, 200)];
[self.view addSubview:textView];
[Operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
textView.text=[NSString stringWithFormat:@"%@:%@",[responseObject class],responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
textView.text=[NSString stringWithFormat:@"Error=%@",[error localizedDescription]];
}];
[[NSOperationQueue mainQueue] addOperation:Operation];
}
- (void)getLogin
{
//1.管理器
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//2.设置登录参数
NSDictionary *dict = @{ @"username":@"xn", @"password":@"123" };
//3.请求
[manager GET:@"http://localhost/login.php" parameters:dict success: ^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"GET --> %@, %@", responseObject, [NSThread currentThread]); //自动返回主线程
} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@", error);
}];
}
/**
* 和上面的GET用法完全一样, 只有一个POST参数不一样
*/
- (void)postLogin
{
//1.管理器
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//2.设置登录参数
NSDictionary *dict = @{ @"username":@"xn", @"password":@"123" };
//3.请求
[manager POST:@"http://localhost/login.php" parameters:dict success: ^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"POST --> %@, %@", responseObject, [NSThread currentThread]); //自动返回主线程
} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@", error);
}];
}