情景是。
1)我已经存在适用于iPhone设备的iOS应用程序。该应用程序在仪表板页面中显示实时数据。 通过从iOS应用程序调用Web服务,每60秒更新一次仪表板上的数据。
2)我想开发基于相同iPhone应用程序的Apple Watch应用程序,每隔60秒就会显示一次数据更新的仪表板。
如何实现这一目标。任何建议都非常感谢。感谢。
答案 0 :(得分:1)
我有相同的场景要执行。所以我在我的应用程序中所做的是:
didFinishLaunchingWithOptions
AppDelegate.m
方法
timer = [NSTimer scheduledTimerWithTimeInterval:120 target:self selector:@selector(refreshData) userInfo:nil repeats:YES];
refreshData
方法看起来像
-(void)refreshData
{
// Update Database Calls
// below line Save new time when update request goes to server every time.
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"databaseUpdateTimestamp"]; //
}
现在在willActivate
watchKit
方法中添加计时器
timer = [NSTimer scheduledTimerWithTimeInterval:120 target:self selector:@selector(refreshData) userInfo:nil repeats:YES];
refreshData
方法将每隔2分钟向父App调用一次请求。
- (void) refreshData
{
NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:@"database",@"update", nil];
[WKInterfaceController openParentApplication:dic reply:^(NSDictionary *replyInfo, NSError *error)
{
NSLog(@"%@ %@",replyInfo, error);
}];
}
现在在您的App Appate in Parent App中
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply
{
if([userInfo objectForKey:@"update"])
{
NSString *strChceckDB = [userInfo objectForKey:@"update"];
if ([strChceckDB isEqualToString:@"database"])
{
NSDate *dateNow = [NSDate date];
NSDate *previousUpdatedTime = (NSDate*)[[NSUserDefaults standardUserDefaults] objectForKey:@"databaseUpdateTimestamp"];
NSTimeInterval distanceBetweenDates = [dateNow timeIntervalSinceDate:previousUpdatedTime];
if (distanceBetweenDates>120) // this is to check that no data request is in progress
{
[self.timer invalidate]; // your orignal timer in iPhone App
self.timer = nil;
[self refreshData]; //Method to Get New Records from Server
[self addTimer]; // Add it again for normal update calls
}
}
}
else
{
//do something else
}
}
使用此更新数据在WatchKit App中填充您的应用程序仪表板。
一些有用的链接可以帮助您完成此任务:
You can create an embedded framework to share code between your app extension and its containing app。
希望这能帮助你...... !!!