1

我试图了解为 iOS 9 执行快速操作(3D 触摸)。

我希望用户选择 4 个过滤器中的 1 个应用于图像,所以如果我选择第 1 项,我会将 NSUserDefaults.standardUserDefaults() 设置为过滤器,然后使用应用的过滤器显示正确的图片。

在 AppDelete.swift 中:

func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
    var filterType:Int
    switch (shortcutItem.type) {
        ...set filterType
    }

    NSUserDefaults.standardUserDefaults().setInteger(filterType, forKey:"filterType")
    NSUserDefaults.standardUserDefaults().synchronize()        
}

在 ViewController.swift 中:

override func viewDidLoad() {
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(self, selector:"setDefaultFilter", name: UIApplicationWillEnterForegroundNotification, object:nil) // Handle enter from background
    setDefaultFilter()
}

func setDefaultFilter() {
    filterType = defaults.integerForKey("filterType")
    ...
    imageView.image = filterImage(defaultImage!, filter:filters[filterType])
}

但是,当从菜单进入应用程序时,它将始终显示最后一个选择(而不是当前选择)。如果我选择第 1 项,则什么也没有发生。我选择第 3 项,第 1 项将出现。

我也尝试通过 appDelegate 传递参数,结果是一样的。我认为生命周期存在一些问题。

有任何想法吗?

4

2 回答 2

1

NSUserDefaults 将数据写入闪存,可能不会那么快。

UIApplicationDidBecomeActiveNotification你可以再等一会儿,比如观察UIApplicationWillEnterForegroundNotification.

或者您可以使用其他方式来传递参数,例如,作为AppDelegate.

于 2015-10-05T14:38:23.733 回答
0

总是在调用 performActionForShortcutItem 方法之前调用 didFinishLaunchingWithOptions 方法来响应快速操作。因此,我认为您需要检查在 didFinishLaunchingWithOptions 方法中选择了哪种快速操作。如果应用程序不是从快速操作启动的,您只需继续正常的应用程序启动过程。(默认过滤器)

如果您决定在 didFinishLaunchingWithOptions 中处理快速操作,则必须在 didFinishLaunchingWithOptions 中返回 NO。

您可以从我的演示项目中获得更多想法:

https://github.com/dakeshi/3D_Touch_HomeQuickAction

于 2015-12-21T09:18:08.930 回答