8.日历Calendar和时区TimeZone
var calendar:Calendar = Calendar.current //生成日历对象
calendar.locale = Locale(identifier: "zh_CN") //设置日历对象的区域属性
calendar.timeZone = TimeZone(abbreviation: "EST")! //获得给定缩写标识的时区
calendar.timeZone = TimeZone(secondsFromGMT: +28800)! //获得使用格林尼治标准时间的指定秒数初始化的时区
calendar.firstWeekday = 2 //设置日历的第一个工作日
calendar.minimumDaysInFirstWeek = 3 //设置第一周的最小天数为3
calendar.locale //获得日历对象当前区域属性
calendar.timeZone//获得日历对象当前的时区
//判断时期是否为今天、明天、昨天
calendar.isDateInToday(Date())
calendar.isDateInTomorrow(Date())
calendar.isDateInYesterday(Date())
9.使用定时组件Timer执行定时任务
//使用计时器可以每隔一定的时间执行某个函数
class ViewController: UIViewController {
var appleCount = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//定义一个定时器对象,时间间隔为1秒,定时执行的任务代码位于尾部的闭包之中
let time = Timer(timeInterval: 1.0, repeats: false) { (timer) in
print("Timer in a block.")
}
time.fire() //执行
//循环执行
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in
print("scheduledTimer in a block.")
}
//循环执行,使用userInfo传参
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.timerAction(_:)), userInfo: "an apple", repeats: true)
}
@objc func timerAction(_ timer: Timer)
{
if self.appleCount == 3
{
timer.invalidate()//停止定时器
return
}
let parameter = timer.userInfo //获得传递的参数
print("I'm eating \(parameter!).")
self.appleCount += 1
}
}
10.使用UserDefaults和归档方式存取用户数据
ViewController.swift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//UserDefaults类用于保存应用程序的设置和属性以及用户数据
let userDefault = UserDefaults.standard
//存整型
userDefault.set(35, forKey: "MyAge")
userDefault.synchronize()
print(userDefault.integer(forKey: "MyAge"))
//存float
userDefault.set(78.5, forKey: "Percentage")
userDefault.synchronize()
print(userDefault.float(forKey: "Percentage"))
//存double
userDefault.set(3.14159265, forKey: "PI")
userDefault.synchronize()
print(userDefault.double(forKey: "PI"))
//存布尔类型
userDefault.set(true, forKey: "IsPassed")
userDefault.synchronize()
print(userDefault.bool(forKey: "IsPassed"))
//存URL类型
userDefault.set(URL(string:"http://www.coolketang.com")!, forKey: "URL")
userDefault.synchronize()
print(userDefault.url(forKey: "URL")!)
//存字符串类型
userDefault.set("CoolKeTang", forKey: "Company")
userDefault.synchronize()
print(userDefault.string(forKey: "Company")!)
//存数组类型
userDefault.set(["Xcode","Swift"], forKey: "Languages")
userDefault.synchronize()
print(userDefault.array(forKey: "Languages") as! [String])
//存字典类型
userDefault.set(["Name":"Jerry"], forKey: "User")
userDefault.synchronize()
print(userDefault.dictionary(forKey: "User") as! [String : String])
//删除操作
userDefault.removeObject(forKey: "User")
userDefault.synchronize()
print(userDefault.dictionary(forKey: "User") ?? "")
//归档一个对象
let person = Person()
person.name = "Smith"
let personData = NSKeyedArchiver.archivedData(withRootObject: person)
userDefault.synchronize()
userDefault.set(personData, forKey: "Teacher")
let data = userDefault.data(forKey: "Teacher")
let teacher = NSKeyedUnarchiver.unarchiveObject(with: data!) as! Person
print(teacher.name)
}
}
Person.swift
import UIKit
//给类添加一个NSCoding协议,他通过扩展你的数据类以支持编码和解码功能。他的任务就是把数据写到数据缓存,最后持久保存到磁盘中
class Person: NSObject, NSCoding
{
var name: String
required init(name:String="")
{
self.name = name
}
required init(coder decoder: NSCoder)
{
self.name = decoder.decodeObject(forKey: "Name") as? String ?? ""
}
func encode(with coder: NSCoder)
{
coder.encode(name, forKey:"Name")
}
}
11.路径URL的使用详解
let url = URL(string: "http://www.coolketang.com")
url?.absoluteString //获得字符串形式
var secondUrl = url?.appendingPathComponent("demo/login/") //添加子目录
secondUrl?.deletingLastPathComponent() //获得网址对象中的当前目录的上一级目录
secondUrl?.host //获得网址对象的主机名称
secondUrl?.lastPathComponent //获得网址对象的最后一个目录(层级)的名称
let thirdUrl = URL(string: "http://www.coolketang.com:8080/login.action?username=jerry")
thirdUrl?.port //获得网址对象的端口
thirdUrl?.query //获得网址对象的查询参数
thirdUrl?.scheme //获得网址对象的scheme
let targetPath:String = NSHomeDirectory() + "/Documents/music.png"
let fileUrl = URL(string: targetPath)
fileUrl?.pathComponents //通过网址对象的属性,可以轻松获得路径的各个目录
fileUrl?.pathExtension //扩展属性,如果路径属于一个文件,可以通过路径获得文件的扩展名
12.使用DispatchGroup管理线程组
//使用调度组可以将多个线程中的任务进行组合管理,可以设置当多个相同层次的任务完成之后,在执行另一项任务。
print("Start the task and display the Loading animation.")
let group = DispatchGroup() //初始化调度组对象
//同时运行多个任务,每个任务的启动时间是按照加入队列的顺序,结束的顺序则依赖各自具体的任务
let globalQueue = DispatchQueue.global()
//通过异步方法,将传入的block块,放入指定的队列里运行
globalQueue.async(group: group, execute: DispatchWorkItem(block: {
print("Load a user picture from the remote server.")
}))
globalQueue.async(group: group, execute: DispatchWorkItem(block: {
print("Get the annual record of all transactions by user id.")
}))
//当调度组中的任务全部完成后,调用通知方法,完成调度组的任务,并执行接下来的块中的动作
group.notify(queue: globalQueue, execute: {
print("Complete all tasks and hide the Loading animation.")
})
globalQueue.async(group: group, execute: DispatchWorkItem(block: {
print("Get the collection of goods by user id.")
}))
13.使用UIScreen查询设备的屏幕信息
UIScreen.main.availableModes.description //获得屏幕尺寸
UIScreen.screens.count //获得屏幕数量
UIScreen.main.bounds //获得屏幕边界信息
UIScreen.main.nativeBounds //获得屏幕的像素尺寸,不会随屏幕的横竖方向改变而改变
UIScreen.main.nativeScale //获得屏幕的真机比例因子,可以简单的理解为像素数量和点数量的比值
UIScreen.main.brightness //获得屏幕的亮度级别
UIScreen.main.coordinateSpace.bounds //获得屏幕当前的坐标空间的边界信息
UIScreen.main.currentMode?.size //获得与屏幕关联的当前屏幕模式的尺寸
14.使用UIColor设置界面组件的颜色属性
UIColor.orange
UIColor.clear
let color = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
let secondColor = UIColor(white: 1.0, alpha: 0.5)
let thirdColor = UIColor(hue: 0.3, saturation: 0.75, brightness: 0.50, alpha: 1.0) //色相、饱和度、亮度、不透明度
//let image = UIImage()
//let thirdColor = UIColor(patternImage: image) //swift支持将图片作为颜色的使用
color.cgColor
color.withAlphaComponent(0.5)
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
//view.backgroundColor = color
view.backgroundColor = thirdColor