Is it possible to update a today widget to show download progress of a file?
Here is my code for the 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];
}
And then here is where I update the user defaults in the app:
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];
What do I need to change? Is this even possible what I am trying to do? I also want to show a progress bar updating as well.
I was able to solve this using:
CADisplayLink *displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateProgress)];