iOS health kit获取当天数据 少八小时的问题

龙渊之源 2016-06-23 11:14:15
各位,近来闲着无聊就看了一下iOS的healthkit的功能,然后在看了一下官方文档后就开始编写了一个小的demo。可是在demo编写完成后发现,在获得到health的权限后获取数据的时候居然是从八点后开始获得到数据,从而每次获取当天的数据时候就会少八小时,而获取全部数据的时候是正确的。后来我看了博客后发现说是自己自定义一下就可以了。可是我在写了一个当天时间的零点开始方法和当天结束时间后发现它还是从八点后开始获取数据,这个事情有人遇到过吗?又是怎么解决的啊
#import "SecondViewController.h"
#import <HealthKit/HealthKit.h>

@interface SecondViewController ()

@property (nonatomic, strong) HKHealthStore *healthStore;

@end

@implementation SecondViewController

- (void)viewDidLoad {
[super viewDidLoad];

if(![HKHealthStore isHealthDataAvailable])
{
NSLog(@"设备不支持");
}

self.healthStore = [[HKHealthStore alloc] init];

HKObjectType *stepCount = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

NSSet *healthSet = [NSSet setWithObjects:stepCount, nil];

[self.healthStore requestAuthorizationToShareTypes:nil readTypes:healthSet completion:^(BOOL success, NSError * _Nullable error) {
if (success)
{
NSLog(@"获取步数权限成功");
[self readStepCount];
}
else
{
NSLog(@"获取步数权限失败");
}
}];

}

- (void)readStepCount
{
HKSampleType *sampleType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:[self getStartTime] endDate:[self getEndTime] options:HKQueryOptionNone];
NSSortDescriptor *start = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:NO];
NSSortDescriptor *end = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType predicate:predicate limit:0 sortDescriptors:@[start,end] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
if(!error && results){
NSLog(@"%@",results);
int sum=0;
for (int i=0; i<results.count; i++) {
HKQuantitySample *result = results[i];
HKQuantity *quantity = result.quantity;
NSString *stepStr = (NSString *)quantity;
NSString *aaaa = [[NSString stringWithFormat:@"%@",stepStr] stringByReplacingOccurrencesOfString:@" count" withString:@""];
sum+= [aaaa intValue];
}
NSLog(@"%d",sum);
}

}];

[self.healthStore executeQuery:sampleQuery];
}

/**
获取当前时区的时间
*/
-(NSDate *)getEndTime{
NSDate *date = [[NSDate alloc]init];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:date];
NSDate *nowDate = [date dateByAddingTimeInterval:interval];
return nowDate;
}

/**
获取开始时间 当天0时0分0秒
*/
-(NSDate *) getStartTime{
NSDateFormatter *datef = [[NSDateFormatter alloc]init];
datef.dateFormat = @"yyyy-MM-dd";
NSString *stringdate = [datef stringFromDate:[self getEndTime]];
NSDate *tdate = [datef dateFromString:stringdate];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:tdate];
NSDate *nowday = [tdate dateByAddingTimeInterval:interval];
return nowday;
}

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

@end
...全文
192 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
不担心 2016-06-27
  • 打赏
  • 举报
回复
NSTimeZone *zone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];试试
Title: Mastering iOS Frameworks: Beyond the Basics, 2nd Edition Author: Joe Keeley, Kyle Richter Length: 576 pages Edition: 2 Language: English Publisher: Addison-Wesley Professional Publication Date: 2015-05-02 ISBN-10: 0134052498 ISBN-13: 9780134052496 Apple’s iOS SDK provides an amazingly powerful collection of frameworks. But it has been difficult to find detailed and useful knowledge about them–until now. With this book’s practical insights and tested code, you can use Apple’s frameworks to create apps that are more innovative and usable…faster and more reliable…more successful and profitable. Kyle Richter and Joe Keeley focus on intermediate-to-advanced techniques that professional iOS developers can use every day. Their far-reaching coverage ranges from social support to security, Core Data to iCloud–even Apple Watch. Organized as a convenient modular reference, nearly every chapter contains a complete Objective-C sample project. A multi-chapter Game Center case study shows how multiple iOS features can be combined to do even more. All source code may be downloaded at https://github.com/dfsw/icf. Coverage includes: Adding physics-like animation and behaviors to UIViews Using Core Location to determine device location, display customized maps, and implement geofencing Making games and apps social with Leaderboards Accessing music and image collections Building health/fitness apps with HealthKit Integrating with home automation via HomeKit Passing data between platforms using JSON Setting up local and remote notifications Remotely storing and syncing data with CloudKit Accessing app functionality with extensions Effortlessly adding AirPrint support Providing Handoff continuity between iOS 8 and Yosemite devices Getting productive with Core Data Integrating Twitter and Facebook via Social Framework Performing resource-intensive tasks with Grand Central Dispatch Securing user data with Keychain and Touch ID Customizing collection views Making the most of gesture recognizers Creating and distributing “passes” Debugging, instrumenting, and profiling apps Table of Contents Chapter 1. UIKit Dynamics Chapter 2. Core Location, MapKit, and Geofencing Chapter 3. Leaderboards Chapter 4. Achievements Chapter 5. Getting Started with Address Book Chapter 6. Working with Music Libraries Chapter 7. Implementing HealthKit Chapter 8. Implementing HomeKit Chapter 9. Working with and Parsing JSON Chapter 10. Notifications Chapter 11. Cloud Persistence with CloudKit Chapter 12. Extensions Chapter 13. Handoff Chapter 14. AirPrint Chapter 15. Getting Up and Running with Core Data Chapter 16. Integrating Twitter and Facebook Using Social Framework Chapter 17. Working with Background Tasks Chapter 18. Grand Central Dispatch for Performance Chapter 19. Using Keychain and Touch ID to Secure and Access Data Chapter 20. Working with Images and Filters Chapter 21. Collection Views Chapter 22. Introduction to TextKit Chapter 23. Gesture Recognizers Chapter 24. Accessing the Photo Library Chapter 25. Passbook and PassKit Chapter 26. Debugging and Instruments
Sharpen your skills in Swift by designing and deploying seven fully functional applications About This Book Develop a variety of iOS-compatible applications that range from health and fitness to utilities using this project-based handbook Discover ways to make the best use of the latest features in Swift to build on a wide array of applications Follow step-by-step instructions to create Swift apps oriented for the real world Who This Book Is For If you are a competent iOS developer who wants to develop stunning applications with Swift, then this book is for you. Familiarity with Swift programming is assumed. What You Will Learn Get to grips with the basics of Xcode and Swift for application development Create a Photo Sharing application to capture an image, edit it using different features and share it via social media. Develop applications using the WatchKit and exchange data between iPhone and the Watch Use advanced features such as SpriteKit to build a game Install third-party Swift frameworks to improvise on your application development Discover how to simulate home automation with HomeKit Build an application to monitor the user's weight, heart rate and the number of steps for Health Historic Analysis Manipulate media using AVFoundation framework to merge audio and video. In Detail In this book, you will work through seven different projects to get you hands-on with developing amazing applications for iOS devices. We start off with a project that teaches you how to build a utility app using Swift. Moving on, we cover the concepts behind developing an entertainment or social networking related application, for example, a small application that helps you to share images, audio, and video files from one device to another. You'll also be guided through create a city information app with customized table views, a reminder app for the Apple Watch, and a game app using SpriteKit. By the end of this book, you will have the required skillset to develop various types of iOS applications with Swift that can run on different iOS devices. You will also be well versed with complex techniques that can be used to enhance the performance of your applications. Style and approach This book takes a step-by-step approach to help you build apps from scratch and learn the methodology to develop real-time applications using Swift. Table of Contents Chapter 1: Exploring Xcode Chapter 2: Creating a City Information App with Customized Table Views Chapter 3: Creating a Photo Sharing App Chapter 4: Simulating Home Automation with HomeKit Chapter 5: Health Analyzing App Using HealthKit Chapter 6: Creating a Game App Using SpriteKit Chapter 7: Creating an Apple Watch App Chapter 8: AVFoundation

29,027

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧