Created by 大劉 liuxing8807@126.com
這里是Apple官網(wǎng)的說明。
A representation of the state of your app at a moment in time.
NSUserActivity是Apple在iOS8之后推出來做Handoff的,它主要用于對(duì)app記錄用戶的操作,后來NSUserActivity主要用來支持:
- Handoff
- SiriKit
- Spolight search results
創(chuàng)建NSUserActivity的流程:
- 使用app支持的合適的type創(chuàng)建并初始化
NSUserActivity對(duì)象, 類型一般約定為reverse-DNS格式,比如com.myCompany.myApp, type需要在Info.plist中使用key為NSUserActivityTypes配置 - 設(shè)置title
- 為對(duì)象設(shè)置合適的屬性以讓它支持不同的業(yè)務(wù) isEligibleForHandoff、isEligibleForSearch、isEligibleForPublicIndexing
- 配置其他屬性
- 對(duì)于配置了search或public indexing的對(duì)象,配置 contentAttributeSet, keywords, or webpageURL
- 調(diào)用
becomeCurrent()向系統(tǒng)注冊(cè)
支持Handoff
設(shè)置isEligibleForHandoff屬性為true
支持SiriKit
當(dāng)SiriKit需要開啟app的時(shí)候,它會(huì)創(chuàng)建一個(gè)user activity對(duì)象,并且設(shè)置userActivityObj.interaction = INInteraction對(duì)象,具體可以參見SiriKit Programming Guide.
支持Search Results
在未打開任何app的時(shí)候,由上往下拖會(huì)啟用Spotlight:

需要深一步了解Core Spotlight,可以參見:[圖片上傳失敗...(image-55b42-1655180877531)]是官網(wǎng)對(duì)Core Spotlight的說明。
我們做一個(gè)簡(jiǎn)單示例,當(dāng)在Spotlight中搜索One or two or three的時(shí)候啟用我們的App, 并使用User activity做一些事情。
新建一個(gè)iOS 工程:
class RootViewController: UITableViewController {
private let items: Array<String> = ["One", "Two", "Three"]
private let activity: NSUserActivity = NSUserActivity(activityType: "daliu")
override func viewDidLoad() {
super.viewDidLoad()
// cellClass: AnyClass
self.tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cellID")
self.addActivity()
}
func addActivity() -> Void {
// title和keywords都可以在Spotlight搜索結(jié)果中出現(xiàn)
self.activity.title = "activity title here"
self.activity.keywords = Set(arrayLiteral: "One", "Two", "Three")
// 是否將用戶活動(dòng)轉(zhuǎn)交到其他設(shè)備
// self.activity.isEligibleForHandoff = false
self.activity.isEligibleForSearch = true
// 每個(gè)控制器的user activity和搜索結(jié)果都是僅當(dāng)應(yīng)用曾經(jīng)被打開過時(shí)而創(chuàng)建的
// _activity.eligibleForPublicIndexing = YES;
// 自動(dòng)被加入到設(shè)備的搜索結(jié)果索引中
self.activity.becomeCurrent()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
cell.textLabel?.text = self.items[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
let vc = OneViewController()
self.navigationController?.pushViewController(vc, animated: true)
case 1:
let vc = TwoViewController()
self.navigationController?.pushViewController(vc, animated: true)
case 2:
let vc = ThreeViewController()
self.navigationController?.pushViewController(vc, animated: true)
default:
break
}
}
override func restoreUserActivityState(_ activity: NSUserActivity) {
if activity.title == "One" {
let vc = OneViewController()
self.navigationController?.pushViewController(vc, animated: true)
} else if let _ = activity.title?.elementsEqual("Two") {
let vc = TwoViewController()
self.navigationController?.pushViewController(vc, animated: true)
} else if activity.title?.caseInsensitiveCompare("Three") == ComparisonResult.orderedSame {
let vc = ThreeViewController()
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
AppDelegate.m
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow.init(frame: UIScreen.main.bounds)
let rootController = UIStoryboard.init(name: "RootViewController", bundle: nil).instantiateInitialViewController() as! RootViewController
let nivController = UINavigationController(rootViewController: rootController)
self.window?.rootViewController = nivController
self.window?.makeKeyAndVisible()
return true
}
// 監(jiān)聽在Spotlight中的點(diǎn)擊
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
let niv: UINavigationController = self.window?.rootViewController as! UINavigationController
niv.topViewController?.restoreUserActivityState(userActivity)
return true
}
這樣,當(dāng)在Spotlight中搜索one時(shí),就是顯示我們的app, 點(diǎn)擊進(jìn)去就進(jìn)入到了OneViewController.