显示下载进度的通知小部件

Notification Widget showing download progress

是否可以更新今天的小部件以显示文件的下载进度?

这是我的 Today Extension 代码:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder])
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDefaultsDidChange:) name:NSUserDefaultsDidChangeNotification object:nil];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.preferredContentSize = CGSizeMake(320, 50);

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateProgress) name:@"UpdateWidget" object:nil];

    [self updateProgress];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)userDefaultsDidChange:(NSNotification *)notification
{
    [self updateProgress];
}

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

    // If an error is encountered, use NCUpdateResultFailed
    // If there's no update required, use NCUpdateResultNoData
    // If there's an update, use NCUpdateResultNewData

    [self updateProgress];

    completionHandler(NCUpdateResultNewData);
}

- (void)updateProgress
{
    double progress = 0;
    NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.xxx.xxxx"];
    progress = [defaults doubleForKey:@"Percent"];
    _percentLabel.text = [NSString stringWithFormat:@"%0.f%%", progress];

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self updateProgress];
}

然后这是我在应用程序中更新用户默认值的地方:

double currentProgress = totalBytesWritten / (double)totalBytesExpectedToWrite;

NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.xxx.xxxx"];
[defaults setDouble:(currentProgress*100) forKey:@"Percent"];
[defaults synchronize];
[[NSNotificationCenter defaultCenter] postNotificationName:@"UpdateWidget" object:nil];

我需要更改什么?这甚至可能是我想要做的吗?我也想显示进度条更新。

我能够使用以下方法解决此问题:

CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateProgress)];