滚动时Widget数据不会更新 - Swift

时间:2015-11-28 11:32:24

标签: ios swift swift2 today-extension

我有一个包含数据的小部件。当我今天发布扩展时,我的小部件数据正在更新并实时显示。但是当我滚动通知中心并返回到我的小部件时,它不会更新。我尝试了几种不同的方法,但它们没有帮助我。我在下面写了我试过的最后一种方法。

     override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "updateLabels", userInfo: nil, repeats: true)
    }


    func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
        // Perform any setup necessary in order to update the view.

        // If an error is encountered, use NCUpdateResult.Failed
        // If there's no update required, use NCUpdateResult.NoData
        // If there's an update, use NCUpdateResult.NewData
        completionHandler(.NewData)
    }


   func updateLabels() {
        runtimeLabel.text = returnTime() + "     " + returnDay()
    }

    func returnTimeInterval() -> NSTimeInterval {
        let uptime = NSProcessInfo().systemUptime
        return uptime
    }

    func returnTime() -> String {
        dateFormatter.unitsStyle = .Short
        dateFormatter.allowedUnits = [.Day, .Hour, .Minute, .Second]
        dateFormatter.zeroFormattingBehavior = .Pad
        let time = dateFormatter.stringFromTimeInterval(returnTimeInterval())!
        return time
    }

    func returnDay() -> String {
        dateFormatter.unitsStyle = .Short
        dateFormatter.allowedUnits = [.Year, .Month, .Day]
        dateFormatter.zeroFormattingBehavior = .Pad
        let date = NSDate(timeInterval: -returnTimeInterval(), sinceDate: NSDate())
        let formatter = NSDateFormatter()
        formatter.locale = NSLocale.currentLocale()
        formatter.dateStyle = .MediumStyle
        let megaDate = formatter.stringFromDate(date)
        return megaDate
    }

2 个答案:

答案 0 :(得分:1)

我尝试了同样的方法,它使用了以下代码:

@IBOutlet weak var infoLabel: UILabel!
var timer = NSTimer()
var counter = 0

    override func viewWillAppear(animated: Bool) {
            super.viewWillAppear(animated)

            timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateLabel"), userInfo: nil, repeats: true)
        }

    func updateLabel(){
            counter += 1
            myLabel.text = "Test \(counter)"
        }

更新

当窗口小部件处于活动状态时应调用<{viewWillAppearviewDidAppear,并在滚动时调用viewDidDisappear(离开窗口小部件)。至于现在,viewDidDisappear按预期工作,但滚动时不是viewWillAppearviewDidAppear

这是一个众所周知的错误,因为它无法正常运行,您可以在Apples论坛的post中阅读更多信息,并查看错误状态报告here

答案 1 :(得分:0)

您应该使用widgetPerformUpdateWithCompletionHandler方法编写更新代码。