一、下载
同步下载三种方法
//网页下载 NSURL *url=[NSURL URLWithString:@"http://www.baidu.com/?tn=96581013_hao_pg"]; NSString *str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil] ; NSLog(@"000000%@",str);
2.//根据下载方法需要什么,定义什么 NSURL *url=[NSURL URLWithString:@"http://www.baidu.com/img/bdlogo.png"]; NSURLRequest *request=[NSURLRequest requestWithURL:url]; //创建指针 NSURLResponse *response; NSError *error; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; //如果下载失败就打印fail if (error) { NSLog(@"fail"); return; } //将response强制转化为NSHTTPURLResponse类型,因为statusCode是NSHTTPURLResponse的一个属性 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; //请求成功状态码为200,写入文件 if (httpResponse.statusCode == 200) { [data writeToFile:@"/Users/apple/Desktop/test.png" atomically:YES]; }
3. NSURL *url=[NSURL URLWithString:@"http://www.baidu.com/img/bdlogo.png"]; //读取网络URL里面的内容 NSData *data=[NSData dataWithContentsOfURL:url]; //将data内容写入文件 [data writeToFile:@"/Users/apple/Desktop/test.png" atomically:YES];
异步下载二种方法
2.根据协议封装下载文件
在down.h中
#import <Foundation/Foundation.h> @class download; //定义协议及协议方法 @protocol downloaddelegate<NSObject> @optional -(void)downloadprocess:(float)process; @required -(void)downloadfinished:(download *)down; @end //挂出下载协议方法 @interface download : NSObject <NSURLConnectionDataDelegate> @property(nonatomic,weak)id<downloaddelegate>delege; @property (nonatomic, copy) NSString *path; @property (nonatomic, copy)NSMutableData *data1; -(void)download; - (void)start; @end
在down.m中
#import "download.h" @interface download() { NSURLConnection *connection; long long totallegth; } @end @implementation download - (id)initWithPath:(NSString *)path { if (self = [super init]) { self.path = path; } return self; } -(void)download { NSURL *url=[NSURL URLWithString:_path]; NSLog(@"路径%@",_path); NSURLRequest *request=[NSURLRequest requestWithURL:url]; connection=[NSURLConnection connectionWithRequest:request delegate:self]; } - (void)start { // 开始下载 [connection start]; } //判断是否出错 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"下载出错%@",error); } //请求响应 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSHTTPURLResponse *httprespose=(NSHTTPURLResponse *)response; if (httprespose.statusCode==200) { totallegth=httprespose.expectedContentLength; } NSLog(@"预计总长度%lld",totallegth); } //接收数据 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { _data1=[[NSMutableData alloc]init]; [_data1 appendData:data]; //对于Optional修饰的方法,需要做判断后才能调用 if (_delege && [_delege respondsToSelector:@selector(downloadprocess:)]){ NSLog(@"下载选择"); [_delege downloadprocess:(float)_data1.length/totallegth]; } } //下载完成 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { //3. 使用指针调用协议方法 NSLog(@"调用协议的方法。。。"); [_delege downloadfinished:self]; } @end
在ViewController.m中
#import "ViewController.h" #import "download.h" @interface ViewController() <downloaddelegate> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; download *downloader = [[download alloc] init]; downloader.path=@"http://www.baidu.com"; [downloader download]; //在两个类中对象间建立联系 downloader.delege=self; download *downloader2=[[download alloc] init]; downloader2.path=@"https://github.com/nicklockwood/iVersion"; [downloader2 download]; downloader2.delege=self; // Do any additional setup after loading the view, typically from a nib. } //协议中必须实现的方法 -(void)downloadfinished:(download *)down { NSString *str = [[NSString alloc] initWithData:down.data1 encoding:NSUTF8StringEncoding]; NSLog(@"下载完成。。%@",str); } //协议中可选实现的方法 -(void)downloadprocess:(float)process { NSLog(@"下载正在进行。。"); NSLog(@"progress进程: %.2f", process); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
二、协议
OC协议:实际上就是两个对象直接的通信
一个对象的任务让另一个对象完成,也叫代理模式。
协议的工作流程:
类A 类B
类A不想实现,因此需要外包出去
1)先制定一个协议(方法列表) 1)如果类B想接单,需先具备资质(挂出协议)
2)类A的对象需要能找到类B的对象(delegate指针引用) 2)类B需要实现require的方法,可选实现optional的方法
3)类A的对象想完成这些工作时,通过代理让类B的对象干活
列子如下:
先制定协议
@protocol BiteDelegate <NSObject> //可选实现方法 @optional - (void)bitepeople:(id)someone; @end
在Person.h中
#import <Foundation/Foundation.h> #import "BiteDelgate.h" #import "Dog.h" #import "Cat.h" @interface Person : NSObject //设置Dog属性 @property(nonatomic,strong) Dog *dog; @property(nonatomic,strong) Cat *cat; @property(nonatomic,strong)id<BiteDelegate>delegate; @end
在Person.m中
#import "Person.h" #import "Dog.h" #import "Cat.h" @implementation Person @end
在Dog.h中
#import <Foundation/Foundation.h> #import "BiteDelgate.h" //挂出协议 @interface Dog : NSObject <BiteDelegate> @end
在Dog.m中
#import "Dog.h" @implementation Dog -(void)bitepeople:(id)someone { NSLog(@"咬死他"); } @end
在Cat.h中
#import <Foundation/Foundation.h> @interface Cat : NSObject @end
在Cat.m中
#import "Cat.h" @implementation Cat @end
三、数据解析
1.Json解析
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // json里面只有5种数据类型NSsting、NSdictiongnary,NSnumber、NSarray、Bool; NSString *jsonStr = @"{"name":"Zhangsan","age":20,"dog":{"name":["XiaoHei", "XiaoQiang"]}}"; NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding]; //将Json数据转化为OC的对象 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; // 打印字典 NSLog(@"%@", dict); // 打印字典内键为“dog”的内容 NSLog(@"%@", dict[@"dog"][@"name"]); // 创建字典对象,并用字典dict的dog字典对其初始化 NSDictionary *dogDict = [dict objectForKey:@"dog"]; // 把字典里的name键所对应内容放入数组内 NSArray *array = [dogDict objectForKey:@"name"]; NSLog(@"%@", array); // 创建字符串并把数组的第一个元素对其进行初始化 NSString *name = [array objectAtIndex:0]; NSLog(@"%@", name); // 创建一个NSNumber对象,并将dict中age所指向的内容对其进行初始化 NSNumber *num = [dict objectForKey:@"age"]; NSLog(@"%@", num); //字典、数组、数值、字符串 NSArray *arr = @[@123, @"123", @{@"name": @"Lisi", @"age": @30}]; //将OC的对象转化为Json数据 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil]; NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"%@", str); // 将str写入"/Users/apple/Desktop/test.json"内 [str writeToFile:@"/Users/apple/Desktop/test.json" atomically:YES encoding:NSUTF8StringEncoding error:nil]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
2.xml解析
#import "ViewController.h" #import "XMLDictionary.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSString *xmlstr=@"<person sex="female"><firstname>Anna</firstname><lastname>Smith</lastname></person><person><sex>female</sex><firstname>Anna</firstname><lastname>Smith</lastname></person>;"; //xml 都是转化为字典 NSDictionary *dic=[NSDictionary dictionaryWithXMLString:xmlstr]; NSLog(@"%@",dic); NSLog(@"%@",[dic objectForKey:@"firstname"]); // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
3.HTML解析
1)1.引入解析工具
2)添加如图所示框架
3)在build setting中加入"/usr/include/libxml2" 到 "header search paths"
4)引入头文件
#import "ViewController.h" #import "HTMLParser.h" #import "HTMLNode.h" #import <libxml/HTMLtree.h>
5)开始解析
#import "ViewController.h" #import "HTMLParser.h" #import "HTMLNode.h" #import <libxml/HTMLtree.h> @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSError *error=nil; NSString *html=[[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://dict.youdao.com/search?le=eng&q=interaction&keyfrom=dict.top"] encoding:NSUTF8StringEncoding error:nil]; // 将HTML转为oc语言 HTMLParser *parser=[[HTMLParser alloc]initWithString:html error:nil]; if (error) { NSLog(@"error:%@",error); return; } // NSLog(@"%@",html); //找body HTMLNode *bodeNode=[parser body]; //根据class找到一个子节点 HTMLNode *htmlnode=[bodeNode findChildOfClass:@"keyword"]; //打印htmlnode里面的内容 NSLog(@"%@",[htmlnode contents]); HTMLNode *html1=[bodeNode findChildOfClass:@"trans-container"]; NSArray *array=[html1 findChildTags:@"li" ]; //将标签里面的东西例举出来 for(HTMLNode *aa in array){ NSLog(@"%@",[aa contents]); }
四、对象之间的传参
1)第一个页面传到第二个页面
在ViewController.m里面
#import "ViewController.h" #import "SecondViewController.h" @interface ViewController () {
//设置全局变量 int i; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIButton *btn=[UIButton buttonWithType:UIButtonTypeSystem]; btn.frame=CGRectMake(100, 200, 100, 40); btn.backgroundColor=[UIColor greenColor]; [btn addTarget:self action:@selector(didclicked) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; i=10; } -(void)didclicked{ SecondViewController *sec=[[SecondViewController alloc]init]; // 将i的值赋值给第一个页面的属性t sec.t=i; [self presentViewController:sec animated:YES completion:nil]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
在SecondViewController.h中
#import <UIKit/UIKit.h> @interface SecondViewController : UIViewController //设置属性 @property int t; @end
在SecondViewController.m中
#import "SecondViewController.h" @interface SecondViewController ()@end @implementation SecondViewController - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { } return self; } - (void)viewDidLoad { [super viewDidLoad]; UIButton *btn=[UIButton buttonWithType:UIButtonTypeSystem]; btn.backgroundColor=[UIColor orangeColor]; btn.frame=self.view.bounds; [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; //打印第一个页面传来的t值 NSLog(@"%d",_t); } -(void)back { [self dismissViewControllerAnimated:YES completion:nil]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end
2.将第二个页面的值传给第一个页面
在ViewController.h里面
#import <UIKit/UIKit.h> @interface ViewController : UIViewController //设置属性 @property int n; @end
在ViewController.m里面
#import "ViewController.h" #import "SecondViewController.h" @interface ViewController ()@end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIButton *btn=[UIButton buttonWithType:UIButtonTypeSystem]; btn.frame=CGRectMake(100, 200, 100, 40); btn.backgroundColor=[UIColor greenColor]; [btn addTarget:self action:@selector(didclicked) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; } -(void)didclicked{ SecondViewController *sec=[[SecondViewController alloc]init]; // 将第二个页面的对象的属性指向第一个页面,实现第二个页面的值传到第一页面必须的留下的地址 sec.viewctr=self; [self presentViewController:sec animated:YES completion:nil]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
在SecondViewController.h中
#import <UIKit/UIKit.h> #import "ViewController.h" @class ViewController; @interface SecondViewController : UIViewController //创建第二个页面的一个属性,使其能够使用这个类的属性,能够实现的第二个页面传到第一个页面 @property ViewController *viewctr; //设置属性 @property int m; @end
在SecondViewController.m中
#import "SecondViewController.h" @interface SecondViewController () { //设置全局变量 int k; } @end @implementation SecondViewController - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { } return self; } - (void)viewDidLoad { [super viewDidLoad]; UIButton *btn=[UIButton buttonWithType:UIButtonTypeSystem]; btn.backgroundColor=[UIColor orangeColor]; btn.frame=self.view.bounds; [btn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; k=5; // 将k的值赋值给给第一个页面的n self.viewctr.n=k; //打印传给第一个页面的值 NSLog(@"n=%d",self.viewctr.n); } -(void)back { [self dismissViewControllerAnimated:YES completion:nil]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
3.通过协议传参
在ViewController.h里面
#import "ViewController.h" #import "SecondViewController.h" @interface ViewController ()<translatedelegate> { SecondViewController *secondCtrl ; int k; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem]; btn.frame = CGRectMake(10, 100, 100, 40); [btn setTitle:@"按钮" forState:UIControlStateNormal]; [btn addTarget:self action:@selector(didClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; // Do any additional setup after loading the view, typically from a nib. } - (void)didClick { secondCtrl = [[SecondViewController alloc] init]; //在两个协议间建立联系 secondCtrl.delegate = self; [self presentViewController:secondCtrl animated:YES completion:nil]; } - (int)fetchValue:(int)value { //传值 k=value; NSLog(@"+++second%@---%d",secondCtrl, k); return 123; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
在SecondViewController.h中
#import <UIKit/UIKit.h> //定义协议 @protocol translatedelegate @optional - (int)fetchValue:(int)value; @end @interface SecondViewController : UIViewController //定义指针用来指向实现协议的对象 @property (nonatomic,weak)id<translatedelegate>delegate; @property (nonatomic, assign) int value; @end
在SecondViewController.m中
#import "SecondViewController.h" @interface SecondViewController () { int k; } @end @implementation SecondViewController - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { self.view.backgroundColor=[UIColor whiteColor]; // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem]; btn.frame = CGRectMake(10, 100, 100, 40); [btn setTitle:@"按钮" forState:UIControlStateNormal]; [btn addTarget:self action:@selector(didClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; // Do any additional setup after loading the view. } - (void)didClick { _value=30; //使用指针来调用协议里面的方法 [self.delegate fetchValue:_value]; [self dismissViewControllerAnimated:YES completion:nil]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end