SDWebImage图片异步下载
1.把SDWebImage包导入到工程中
2.把里面的.m文件在build phase中添加-fno-objc-arc来转换编译模式(在arc中运行)
3.加头文件“UIImageView + WebCache.h”添加UIImageView的扩展类
4.UIImageView类型调用[setImagewithUrl:]来加载网络图片
//使用扩展方法异步下载图片并做本地缓存
//placeholderImage:默认图片显示(当图片没有下载完成时,显示默认图片)
[myImageView setImageWithURL:[NSURL URLWithString:@"http://a.hiphotos.baidu.com/image/w%3D400/sign=7bddb6f4b54543a9f51bfbcc2e168a7b/0bd162d9f2d3572cd91bf4dc8813632762d0c331.jpg"] placeholderImage:[UIImage imageNamed:@"moren.png"]];
网络下载和json解析
1.网络下载基本使用NSURLConnection
C/S结构:client客户端(手机端)和用户进行交互
server服务端(web),为客户提供数据和数据处理的终端
//网络接口的HTTP形式接口(http://192.168.88.8/sns/my/user_list.php?page=1&number=20)get接口
(1)NSSting同步下载
-(void)testStringDownload
{
NSString *urlString = @"http://10.0.8.8/sns/my/user_list.php?page=1&number=20";
NSError *error = nil;
NSURL *url = [NSURL URLWithString:urlString];
NSString *userListData = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
//如果error有值, 下载失败
if(error != nil)
{
NSLog(@"下载失败 Error = %@",error);
return;
}
NSLog(@"userlist = %@",userListData);
}
(2)NSURLConnection同步下载
-(void)urlConnectionSynchronizeDownload
{
NSString *urlString = @"http://10.0.8.8/sns/my/user_list.php?page=1&number=20";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if(error != nil)
{
NSLog(@"数据下载失败 error = %@",error);
return;
}
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"str = %@",str);
}
(3)NSURLConnection异步下载
-(void)urlConnectionAsynchronousDownloadData
{
NSString *urlString = @"http://10.0.8.8/sns/my/user_list.php?page=1&number=20";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 效果: 方法执行之后立即返回, 一旦有数据下载,通知delegate指向的对象
//startImmediately:YES 是否立即执行
_downloadData = [[NSMutableData alloc] init];
_urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"当接受到服务器的响应时执行,开始下载数据");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"当接受到数据时执行, 下载数据较多时执行多次需要把每次下载的数据合并到一起");
[_downloadData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"数据下载完成");
//获取下载的数据
//NSString *str = [[NSString alloc] initWithData:_downloadData encoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_downloadData options:NSJSONReadingMutableContainers error:nil];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"下载失败 error = %@",error);
}
AFNetWork使用(GET&POST)
1.通过域名去判断网络状态
//iphone网络状态(WAN, Wi-Fi, 不可达)
//基本原理: 通过一个域名去判断
(1)创建一个网络请求管理者
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"www.baidu.com"]];
(2).在网络请求的block参数status中返回网络状态
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
1.断网状态下返回:AFNetworkReachabilityStatusNotReachable = 0,
2.移动网络状态(3G,4G)AFNetworkReachabilityStatusReachableViaWWAN = 1,
3.无线网络状态AFNetworkReachabilityStatusReachableViaWiFi = 2
}
(3)可以监听网络的状态变化
//当网络发生变化也会跑到这个block里面
//开启网络状态监视
[manager.reachabilityManager startMonitoring];
2.get请求创建
// http://www.baidu.com/index.php?from=qf
// 特点: 上传的数据放在url的参数中
// url网址每个浏览器有限制的, 约8192字符
// get最好不好上传密码
(1)编写一个urlString作为网址(完整的url地址,包括有参数?后面的元素)
NSString *urlString = @"http://www.baidu.com/";
(2)创建一个网络请求管理者
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//遇到了问题 Code=-1016, 下载的数据不是json
// 以下的解析器类型获取的数据是NSData类型的
(3)配置网络请求的数据类型(一般就使用serializer,确定responseObject是NSData数据类型)
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
(4)GET请求parameters为nil,没有请求Body(最为重要的方法)
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error = %@",error);
}];
3.get请求创建JSon数据请求
NSString *urlString = @"http://10.0.8.8/sns/my/user_list.php?page=1&number=20";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//解析json的时候遇到问题 -1016, 返回NSData
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// content-type: text/html
//manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error = %@",error);
}];
4.post请求
// http://quiet.local/1413/webtest/login/login.php
// "user" = "12321"
// 特点: 数据会放在请求的附加数据中上传, 数据长度没有限制
// 常用于上传密码, 图片, 文件......
-(void)postRequestTest
{
NSString *url = @"http://10.0.8.8/sns/my/register.php”;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//设置请求头
[manager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"pingtai"];
[manager.requestSerializer setValue:@"8.4" forHTTPHeaderField:@"version"];
[manager.requestSerializer setValue:@"sfwffweifj121131dqd" forHTTPHeaderField:@"cookie"];
[manager POST:url parameters:@{@"user":@"text12323",@"password":@"dfefefw",@"email":@"[email protected]"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error = %@",error);
}];
}
5.ImageUrl下载(效果没有SDWebImage好)
-(void)asyncLoadImageTest
{
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
imageView.backgroundColor = [UIColor redColor];
[self.view addSubview:imageView];
//异步加载图片
// setImageWithURL:是由AFNetworking提供的
[imageView setImageWithURL:[NSURL URLWithString:@"http://img0.bdstatic.com/img/image/shouye/zqsjbtlsjb.jpg"]];
}
KVC键值监听
1.把一个id(字典或者是数组)制作成一个Object(类对象)
2.当数组或者字典的key发生变化时候,会报错(可以发现数据接口的变化)
3.把某个key中的value设置为相同名称属性的值
@{@“name”:@“huang”}
[self setValue:@“” ForKey:@“name”];
@property (nonatomic,strong) NSString *name;
把name中的value:huang设置为self.name = huang中的值
4.key值需要有对应的属性,否则报错(名字相同)
5.简单kvc字典编译
(1)通过此方法,遍历dic中所有key
(2)dic中的所有key都需要有对应的属性
[self setValuesForKeysWithDictionary:dic];
XML数据解析
1.配置XML库(配置完才能使用)
(1)添加头文件搜索路径
Build Settings->搜索Header Search Paths-> /usr/include/libxml2
(2)添加二进制库
Build Phases-> Link library -> libxml2.dylib
(3)源文件添加编译选项
-fno-objc-arc
(4)添加头文件
#import "GDataXMLNode.h"
2.GData语法
GDataXMLDocument * doc = [[GDataXMLDocument alloc]initWithData:data options:0 error:nil];
1.单斜杆/ 从根节点一层一层往下搜索节点
NSArray * array = [doc nodesForXPath:@"root/systemConfig/CityName" error:nil];
GDataXMLElement * element = [array firstObject];
//element的名称和对应的值
NSLog(@"stringValue = %@,name = %@",element.stringValue,element.name);
2.双斜杠// 直接把document中的所有该节点名称的节点都获取出来
NSArray * array2 = [doc nodesForXPath:@"//Item" error:nil];
NSLog(@"count = %lu",(unsigned long)array2.count);
GDataXMLElement * element2 = [array2 firstObject];
for(GDataXMLNode * node in element2.attributes){
NSLog(@"name = %@,stringValue = %@",node.name,node.stringValue);
}
3:@语法:寻找相应的属性
//一般用法,@会和双斜杠一起使用(不管属性在哪个节点中,直接把属性获取出来)
NSArray * array3 = [doc nodesForXPath:@"//@value" error:nil];
for(GDataXMLNode * node in array3){
NSLog(@"name = %@,stringValue = %@",node.name,node.stringValue);
}
GData中的一些属性介绍
1.获取根目录节点
GDataXMLElement * root = doc.rootElement;
2.获取子节点数量
NSLog(@"root.childCount = %lu",(unsigned long)root.childCount);
3.获取某个节点的所有子节点
NSArray * array4 = root.children;
4.通过节点的名称直接从父节点中获取某个节点
NSArray * array5 = [root.children[0] elementsForName:@"areaCode"];
GDataXMLElement * areaElement = [array5 firstObject];
5.获取结点的属性
for(GDataXMLElement *attr in item.attributes)
{
NSLog(@"attr name: %@, value: %@",attr.name,attr.stringValue);
}
下拉刷新JHRefresh库
入参数1:AniViewClass(下拉下来的显示类型)
普通文字刷新 [JHRefreshCommonAniView class]
大众点评刷新 [JHRefreshAmazingAniView class]
__weak SecondTableViewController *ssself = self;
[self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
//发请求的方法区域
NSLog(@"触发下拉刷新headerView");
//制作一个延时操作 延时后收回下拉的headerView
[self.tableView headerEndRefreshingWithResult:JHRefreshResultFailure]; //展示刷新失败界面,延时隐藏
JHRefreshResultSuccess 展示刷新成功界面,延时隐藏
}];
上拉获取更多
[self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
//发请求的方法区域
//制作一个延时操作
double delayTime = 2.0;
dispatch_time_t dispatchTime = dispatch_time(DISPATCH_TIME_NOW, delayTime *NSEC_PER_SEC);
//两秒以后回到主线程调用方法
dispatch_after(dispatchTime, dispatch_get_main_queue(), ^{
[ssself.tableView footerEndRefreshing]; //收回上拉的footView
NSLog(@"延时操作方法区域");
});
}];
三种延时方法
1.NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:ssself selector:@selector(hideHeaderView) userInfo:nil repeats:NO];
2. 入参数:1.方法名 2.传参 3.延时时间
[ssself performSelector:@selector(hideFootView) withObject:nil afterDelay:2];
3.double delayTime = 2.0;
dispatch_time_t dispatchTime = dispatch_time(DISPATCH_TIME_NOW, delayTime *NSEC_PER_SEC);
//两秒以后回到主线程调用方法
dispatch_after(dispatchTime, dispatch_get_main_queue(), ^{
NSLog(@"延时操作方法区域");
});
FMDB库的配置
<1> 把FMDB库文件拖捡来
<2> 添加二进制库 sqlite3.dylib
<3> 包含头文件 #import "FMDatabase.h"
SQLite数据库
创建数据库NSHomeDirectory()沙盒目录
NSString * filePath = [NSString stringWithFormat:@"%@/Documents/data.sqlite",NSHomeDirectory()];
self.dataBase = [[FMDatabase alloc]initWithPath:filePath];
1.打开数据库
[self.dataBase open];
2.创建表单
NSString * sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(name varchar(32),age varchar(32))",tableName];
BOOL isCreate = [self.dataBase executeUpdate:sql];
3.插入数据
NSString * sql = [NSString stringWithFormat:@"INSERT INTO %@(name,age) VALUES('pascal','21')",tableName];
BOOL isInsert = [self.dataBase executeUpdate:sql];
4.删除数据
NSString * name = @"pascal";
NSString * sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE name = ?",tableName];
BOOL isDelete = [self.dataBase executeUpdate:sql,name];
5.查找数据
NSString * name = @"pascal";
NSString * sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE name = ?",tableName];
FMResultSet * result = [self.dataBase executeQuery:sql,name];
while([result next]){
for(int i = 0; i < fieldArray.count; i++){
NSString * str = [result stringForColumnIndex:i];
NSLog(@"%@ = %@",fieldArray[i],str);
}
或者
for(NSString * key in fieldArray){
NSString * value = [result stringForColumn:key];
NSLog(@"key = value",key = value);
}
}
6.修改数据
NSString * sql = [NSString stringWithFormat:@"UPDATE %@ SET name = 'iceice' WHERE name = 'pascal'",tableName];
BOOL isUpdate = [self.dataBase executeUpdate:sql];
7.关闭数据库
[self.dataBase close];
SQL基本语法(重点)
1.修改操作关键字
(1)增:(关键字)insert
(2)删:delete
(3)改:update
(4)查:select
2.常使用关键字
(1)在哪里执行操作:from+数据表
(2)加在哪个位置into +数据表(与insert一起使用)
(3)条件语句:where
3.修饰关键字
(1)top +条数(前面十条数据)
(2)order by + 字段名 (按照这个名来排序)
(3)[desc]升降序标示
(4)like (与这个字段相似)
(5)in+多个值(选取这几个值)
(6)between +两个值(两个值之间的所有值)
CoreData 简介
1、iOS开发中实现数据持久化存储的⼀种重要手段。
2、CoreData提供了对象-关系映射的功能,能将 Objective-c的对象使⽤用数据库或者XML等⽅方式 存储。
3、如果使⽤用CoreData将数据存到数据库中,不 ⽤用通过sql语句来操作数据
CoreData核心类
1、NSManagedObjectModel,⽤用来加载
coreData数据模型⽂文件,所有的数据模型可以 全部加载到此对象中。
2、NSManagedObjectContext,⽤用于操作数据 模型(对象),并监测数据模型(对象)的变化。
3、NSPersistentStoreCoordinator, 数据 持久化存储协调器,负责调度上层与底层对数据的
操作。4、NSManagedObject, 具体的数据模型对象
5、NSEntityDescription,模型描述类,能够
实例化得到具体的数据模型对象 6、NSFetchRequest,数据查询请求类
7、NSPredicate,通过谓词设置查询条件的类 (正则表达式)
CoreData的使用
1.创建CoreData文件
2.添加CoreData模型
3.加载CoreData文件
#数据库准备
1.取出CoreData文件路径
NSString * filePath = [[NSBundle mainBundle]pathForResource:@"Model" ofType:@"momd"];
2.取出CoreData在工程中的模型
NSManagedObjectModel * model = [[NSManagedObjectModel alloc]initWithContentsOfURL:[NSURL fileURLWithPath:filePath]];
3.制作一个关联层(用于coreData和数据库sqlite的关联)
self.coor = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];
4.制作一个数据库地址
NSString * dBfilePath = [NSString stringWithFormat:@"%@/Documents/data.sqlite",NSHomeDirectory()];
5.关联层创建数据库返回对象
//入参:(1)Type:设置关联类型为数据库sqlite
(2)URL:设置需要关联的数据库地址
NSPersistentStore * store = [self.coor addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:dBfilePath] options:0 error:nil];
6.制作一个操作对象
self.context = [[NSManagedObjectContext alloc]init];
7.获取数据库和coreData的关联层
self.context.persistentStoreCoordinator = self.coor;
#数据库操作
1.添加数据
-(void)insertData{
//从表单中创建一个将要插入到表单中的Person对象
Person * p = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
p.name = @"iceice";
p.age = @"21";
p.gender = @"0";
NSError * error;
if([self.context save:&error]){
NSLog(@"插入成功");
}else{
NSLog(@"插入失败 error= %@",error.localizedDescription);
}
}
2.删除数据
-(void)deleteData{
//创建一个查询返回结果对象
NSFetchRequest * request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
//把查询结果转化成数组数据
NSArray * dataArray = [self.context executeFetchRequest:request error:nil];
NSLog(@"dataArray = %@",dataArray);
for(Person * p in dataArray){
NSLog(@"name = %@",p.name);
[self.context deleteObject:p]; //删除对象(删除数据库某条数据)
//[self.context deleteObjects]; //删除所有数据(清空表单)
[self.context save:nil]; //操作完数据库 需要保存
}
}
3.查询数据
-(void)seleteData{
NSFetchRequest * request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
//设置查询条件
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@",@"bing"];
//把predicate加载到request
[request setPredicate:predicate];
NSArray * dataArray = [self.context executeFetchRequest:request error:nil];
for(Person * p in dataArray){
NSLog(@"name = %@",p.name);
NSLog(@"age = %@",p.age);
}
}
4.修改数据
-(void)updateData{
NSFetchRequest * request = [[NSFetchRequest alloc]initWithEntityName:@"Person"];
NSArray * dataArray = [self.context executeFetchRequest:request error:nil];
for(Person * p in dataArray){
p.name = @"bing";
}
[self.context save:nil];
}
工程的生命周期
1.工程开始时的UI入口
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
2.工程进入后台的状态时调用(按home键后)
- (void)applicationDidEnterBackground:(UIApplication *)application
3.返回到前台调用的方法
- (void)applicationWillEnterForeground:(UIApplication *)application
4.工程销毁时调用的方法
- (void)applicationWillTerminate:(UIApplication *)application
第三方库MagicalRecord使用
1.在工程开始时的UI入口创建数据库
[MagicalRecord setupCoreDataStackWithStoreNamed:@"data.sqlite"];
2.在工程销毁时清理数据库
数据库的clearUp清理
[MagicalRecord cleanUp];
3.添加数据
-(void)insertData{
Person * p = [Person MR_createEntity];
p.name = @"Rapunzel";
p.age = @"22";
p.gender = @"0";
[[NSManagedObjectContext MR_defaultContext]MR_saveToPersistentStoreAndWait];
}
4.删除数据
-(void)deleteData{
NSArray * arr = [Person MR_findByAttribute:@"name" withValue:@"Rapunzel"];
for(Person * p in arr){
[p MR_deleteEntity];
}
}
5.修改数据
-(void)updateData{
NSArray * arr = [Person MR_findAll];
for(Person * p in arr){
p.name = @"Pascal";
NSLog(@"name = %@",p.name);
}
[[NSManagedObjectContext MR_defaultContext]MR_saveToPersistentStoreAndWait];
}