0
回答
iOS无法将数据共享至Apple Watch

 

已经设置好手机APP的Target的AppGroups的ID以及WatchAPPTarget的APPGroups的ID相同,通过NSUserDefaults方法将数据本地化保存,无法从WatchAPP中将数据读出来。
//IOS端代码,读取步数信息函数,并本地化保存数据,共享至AppleWatch
-(void)readStepData{
    /**********方法二开始,得出结果为总步数,问题:查询出的步数有问题,结果为所有步数,并不是当天所有步数***********/
    HKQuantityType *type = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    //过滤条件
    NSCalendar * calendar = [NSCalendar currentCalendar];
    NSDate * now = [NSDate date];
    
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    
    //开始日期
    NSDate *startDate = [calendar dateFromComponents:components];
    //结束日期
    NSDate *endDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:startDate options:0];
    
    NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];
    
    HKObserverQuery *query = [[HKObserverQuery alloc]initWithSampleType:type predicate:predicate updateHandler:^(HKObserverQuery * _Nonnull query, HKObserverQueryCompletionHandler  _Nonnull completionHandler, NSError * _Nullable error) {
        HKStatisticsQuery *sQuery = [[HKStatisticsQuery alloc]initWithQuantityType:type quantitySamplePredicate:nil options:HKStatisticsOptionCumulativeSum completionHandler:^(HKStatisticsQuery * _Nonnull query, HKStatistics * _Nullable result, NSError * _Nullable error) {
            HKQuantity *quantity = result.sumQuantity;
            NSInteger stepCount = [quantity doubleValueForUnit:[HKUnit countUnit]];
            NSLog(@"startDate:%@",startDate);
            NSLog(@"endDate:%@",endDate);
            NSLog(@"stepCount:%ld",stepCount);
            NSString *stepNumberString = [NSString stringWithFormat:@"%ld", stepCount];
            //设置共享
            NSUserDefaults *defaults = [[NSUserDefaults alloc]initWithSuiteName:@"group.beancurd.walker"];
            [defaults setObject:stepNumberString forKey:@"stepNumberString"];
            [defaults synchronize];
        }];
        [_health executeQuery:sQuery];
    }];
    [_health executeQuery:query];
    
  /**********方法二结束,得出结果为总步数***********/
}

//Watch端代码,读取IOS共享的数据,判断数据不为空可设置label
-(void)updateStepNumber{
    NSUserDefaults *defaults = [[NSUserDefaults alloc]initWithSuiteName:@"group.beancurd.walker"];
    
    //_stepNumber = [defaults integerForKey:@"stepNumber"];
    _stepNumberString = [defaults objectForKey:@"stepNumberString"];
    
    NSLog(@"总步数:%@", _stepNumberString);
    if (_stepNumberString) {
        [_stepNumberLabel setText:_stepNumberString];
    }else{
        [_stepNumberLabel setText:@"100"];
        NSLog(@"没有数据");
    }
}
相关图文详情可转向此地址查看:http://www.cocoachina.com/bbs/read.php?tid=1716539&page=1&toread=1#tpc

举报
大豆腐
发帖于1年前 0回/142阅
顶部