我正在制作健康应用程序。我想在Swift中从@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/categories")
public POSResponse getAllCategories() {
String countryCode="1";
return infoService.getAllCategories(countryCode);
}
获取 @Mock
InfoService infoService;
@InjectMocks
private InfoController infoController;
private MockMvc mockMvc;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(infoController).build();
}
@Test
public void getAllCategoriesTest() throws Exception {
POSResponse response=new POSResponse();
Category category=new Category();
category.setCountryCode(1);
category.setDescription("Mother Dairy");
response.setResponse(category);
when(infoService.getAllCategories("1")).thenReturn(response);
mockMvc.perform(get("/categories"))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.id", is(1)))
.andExpect(jsonPath("$.description", is("Mother Dairy")));
verify(infoService, times(1)).getAllCategories("1");
verifyNoMoreInteractions(infoService);
}
。但是,我有一个问题。返回值为0.0英里。
为什么返回值是0英里?
我的代码是这样的。
walkingRunningDistance
答案 0 :(得分:5)
如果
,您的代码将返回一个值
- 您已请求用户许可阅读 来自HealthKit的distanceWalkingRunning
- 用户已授予您的应用权限。
醇>
如果没有,您的代码将返回0.
要请求授权,您可以致电
func requestAuthorization(toShare typesToShare: Set<HKSampleType>?, read typesToRead: Set<HKObjectType>?, completion: @escaping (Bool, Error?) -> Swift.Void)
typesToRead
包含
let distanceType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!
我相信使用HKStatisticsQuery或HKStatisticsCollectionQuery会更有效率。这是一个例子。
guard let type = HKSampleType.quantityType(forIdentifier: .distanceWalkingRunning) else {
fatalError("Something went wrong retriebing quantity type distanceWalkingRunning")
}
let date = Date()
let cal = Calendar(identifier: Calendar.Identifier.gregorian)
let newDate = cal.startOfDay(for: date)
let predicate = HKQuery.predicateForSamples(withStart: newDate, end: Date(), options: .strictStartDate)
let query = HKStatisticsQuery(quantityType: type, quantitySamplePredicate: predicate, options: [.cumulativeSum]) { (query, statistics, error) in
var value: Double = 0
if error != nil {
print("something went wrong")
} else if let quantity = statistics?.sumQuantity() {
value = quantity.doubleValue(for: HKUnit.mile())
}
DispatchQueue.main.async {
completion(value)
}
}
healthStore.execute(query)
答案 1 :(得分:0)
healthStore =[HKHealthStore new];
HKQuantityType *stepType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKSampleType *sleepType = [HKSampleType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
HKQuantityType *walkType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning];
NSArray *arrayType = @[stepType,sleepType,walkType];
[healthStore requestAuthorizationToShareTypes:[NSSet setWithArray:arrayType]
readTypes:[NSSet setWithArray:arrayType] completion:^(BOOL succeeded, NSError *error) {
if (succeeded) {
NSLog(@"Not working");
NSLog(@"error %@",error);
} else {
NSLog(@"Working!");
NSLog(@"error %@",error);
}
[self getStepCount];
}];
以上获取访问权限的方法和以下获取计数的方法
-(void)getStepCount{
NSInteger limit = 0;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:1372418789];
// Divided by 1000 (i.e. removed three trailing zeros) ^^^^^^^^
NSString *formattedDateString = [dateFormatter stringFromDate:startDate];
// Fri, 28 Jun 2013 11:26:29 GMT
NSLog(@"start Date: %@", formattedDateString);
NSDateFormatter *dateFormatter1=[[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"%@",[dateFormatter1 stringFromDate:[NSDate date]]);
NSString *dateString =[dateFormatter1 stringFromDate:[NSDate date]];
NSDate *endDate = [dateFormatter1 dateFromString:dateString];
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictEndDate];
HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierDistanceWalkingRunning]
predicate: predicate
limit: limit
sortDescriptors: nil
resultsHandler:^(HKSampleQuery *query, NSArray* results, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
// sends the data using HTTP
int dailyAVG = 0;
NSLog(@"result : %@",results);
for(HKQuantitySample *samples in results)
{
NSLog(@"dailyAVG : %@",samples);
}
NSLog(@"dailyAVG : %d",dailyAVG);
NSLog(@"%@",@"Done");
});
}];
[healthStore executeQuery:query];
}
答案 2 :(得分:0)
在项目功能中启用HealthKit并将必要的“隐私-Health Share使用说明”键添加到info.plist文件中...
通过将其添加到ViewController.swift(实际上是在viewDidLoad()函数中)来确保您正在请求用户的批准。
1535320256
然后创建getSteps()函数。
let store = HKHealthStore()
let stepType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let woType = HKObjectType.workoutType()
store.requestAuthorization(toShare: [], read: [stepType, woType], completion: { (isSuccess, error) in
if isSuccess {
print("Working")
self.getSteps()
} else {
print("Not working")
}
})