常用操作 | Swift

一些 Swift 的常用操作。

发送本地通知

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// 发送通知
func sendNotification(title: String, subtitle: String = "", informativeText: String = "") {
let userNotification = NSUserNotification()
userNotification.title = title
userNotification.subtitle = subtitle
userNotification.informativeText = informativeText

let userNotificationCenter = NSUserNotificationCenter.default
userNotificationCenter.delegate = self
userNotificationCenter.scheduleNotification(userNotification)
}

// 当 App 在前台时是否弹出通知
func userNotificationCenter(_ center: NSUserNotificationCenter, shouldPresent notification: NSUserNotification) -> Bool {
return true
}

// 推送消息后的回调
func userNotificationCenter(_ center: NSUserNotificationCenter, didDeliver notification: NSUserNotification) {
print("\(Date(timeIntervalSinceNow: 0)) -> 消息已经推送")
}

// 用户点击了通知后的回调
func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) {
switch notification.activationType {
case .actionButtonClicked:
let method = notification.userInfo!["method"] as! String
print("methods -> \(method)")
case .contentsClicked:
print("clicked")
case .replied:
print("replied")
case .additionalActionClicked:
print("additional action")
default:
print("action")
}
}

固定间隔循环执行

1
2
3
4
let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { _ in
print("\(Date(timeIntervalSinceNow: 0))")
})
RunLoop.main.add(timer, forMode: .common)

这个操作是只有一个线程在做,必须这一次执行完后下一次才能开始。

请求相机权限

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let status = AVCaptureDevice.authorizationStatus(for: .video)

if status == .authorized {
// connect to video device
}

if status == .denied {
// show error
}

// 如果需要,使用 requestAccess(for:completionHandler:) 请求权限
AVCaptureDevice.requestAccess(for: .video) { (accessGranted) in
// handle result
}

请求辅助功能权限

1
2
3
4
5
6
7
8
let key = kAXTrustedCheckOptionPrompt.takeRetainedValue() as String
if (!AXIsProcessTrustedWithOptions([key: true] as CFDictionary)) {
// Sometimes Prompt option above doesn't work, actually trying to send key may open that dialog.
let src = CGEventSource(stateID: .hidSystemState)
// "Fn" key down and up
CGEvent(keyboardEventSource: src, virtualKey: 63, keyDown: true)?.post(tap: .cghidEventTap)
CGEvent(keyboardEventSource: src, virtualKey: 63, keyDown: false)?.post(tap: .cghidEventTap)
}

延迟执行

1
2
3
4
5
6
7
// 阻塞当前线程
sleep(5)

// 新建一个线程
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) {
// do something
}
作者

zhongtian

发布于

2020-02-03

更新于

2023-12-16

许可协议

评论