前言
通过将数据缓存在本地,可以有效减少http请求数,和提升用户体验。
本文章要解决的问题:要保存数据。1.首先要知道什么时候保存恰当?2.然后要知道怎么保存?即是用什么类(class)和方法(method)?
App Life Cycle
要了解iOS如何将数据存在本地,先来了解一个App的生命周期(App Life Cycle).
一个App的状态
或者你已经注意到了,App有两个表示正在运行的状态(state)
- Active.这状态(state) 表示app正在远行,并且占据控制整个屏幕。
- Background.这状态表示app正在运行,但是没有占据控制整个屏幕。例如:我们打开微信回复微信,并且使用网易云音乐听歌。其中网易云音乐就是处于Backgruond.
当然,除了表示正在运行的状态,也有表示不在远行的状态(state)
- Not Running.表示这个App还没有打开过。
- Inactive.表示这个App曾经打开过并且运行的,但遇到user(用户)按下了home键,或者是收到了电话。
如下,第五的状态是很少见到的。
- Suspended.表示App 可在后台(background)运行,但是没有做任何事情。
这些状态的转换都会作为app生命周期事件(app lifecycle event)传递给AppDelegate.
Life Cycle Method
状态转换是通过Delegate通知AppDelegated,其中管理状态转换(Managing State Transitions)的Delegate method,如下:以下两个method是,Not Running 转 Active 状态
- application(_:willFinishLaunchingWithOptions:)
- application(_:didFinishLaunchingWithOptions:)
以下这method是任一 state 转为 Active状态
- applicationDidBecomeActive(_:)
- applicationWillResignActive(_:)
以下method如其名字所说
- applicationDidEnterBackground(_:)
- applicationWillEnterForeground(_:)
这method是转为Not running时
- applicationWillTerminate(_:)
例子
将上面AppDelegate的method中加入相应print语句观察状态转换。
按照相应gif的操作,在终端有如下输出:
第一次启动时
App Delegate: will finish launchingApp Delegate: did finish launchingApp Delegate: did become active
按下home键时
App Delegate: will resign activeApp Delegate: did enter background
按下app按钮回到Foreground时
App Delegate: will enter foregroundApp Delegate: did become active
lock的时候
App Delegate: will resign activeApp Delegate: did enter background
解锁的时候
App Delegate: will enter foregroundApp Delegate: did become active
双机home键然后向上滑动结束app
App Delegate: will terminate也可以是App Delegate: did enter background.关键是看app是否支持background 执行.
保存数值的类和方法
了解完一个app的state转换。然后就到用什么类了。其它更多特性的类和方法,留在以后章节介绍。这里是使用比较简单的类。能用它保存用户设定的值
NSUserDefaults 保存值
用NSUserDefaults保存数值
NSUserDefaults.standardUserDefaults().defaults.setFloat(22.5 forKey: “myValue”)
用NSUserDefaults取回数值
let value = NSUserDefaults.standardUserDefaults().floatForKey(“myValue”)
保存文件
app文件保存目录
每个app都是独立的。沙盒结构。app目录
-
Documents/
目录这里保存着user可以访问的files,面向user的files。 -
Library/Application support/
目录通常来说,这目录保存这一个app运行需要的file,但是对user隐藏。 -
Documents/
andApplication Support/
目录默认是自动备份的 -
tmp/
目录系统会清除里面的数据,当app不再运行时。 -
Library/Caches/
目录这目录下的数据比tmp/
目录下的数据活得旧一点,但是相比Support/
目录下活得短一点因为系统会删除Caches/
来解放存储空间。所以这些数据file应该可以是重新获取的。
建立FilePath
let filename = "usersVoice.wav" let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String let pathArray = [dirPath, filename] let fileURL = NSURL.fileURLWithPathComponents(pathArray)!
用NSFileManager检查文件是否存在
if NSFileManager.defaultManager().fileExistsAtPath(audioFileURL().path!) { shouldSegueToSoundPlayer = true }