2017-10-09 133 views
0

我從我的目標c應用程序中讀取我iPhone的健康值。 我只需要閱讀最近10天,但我無法做一個查詢來做到這一點。如何從healthkit獲得最近10天的時間?

我試圖用這個代碼添加到謂詞查詢:

NSPredicate *explicitforDay = 
[NSPredicate predicateWithFormat:@"%K >= %@ AND %K <= %@", 
HKPredicateKeyPathDateComponents, startDateComponents, 
HKPredicateKeyPathDateComponents, endDateComponents]; 

然後我嘗試這樣做:

NSPredicate *explicitforDay = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ < %%@ AND %@ >= %%@", HKPredicateKeyPathStartDate 
                    , HKPredicateKeyPathEndDate], myFirstDate, myEndDate]; 

但在輸出我可以看到一些這樣的:

(的startDate < CAST(529279732.871222 「的NSDate」)日期和結束日期> = CAST(527983732.871222 「的NSDate」) )

爲什麼打印CAST和錯誤的日期值? 謝謝!

+0

我在代碼中看不到任何打印命令,也沒有看到日期的實際值。因此很難說,打印輸出是否正確。 –

回答

0

日期很簡單。我已經爲此here發佈了更長的解釋。

因此,一個簡單的數字被放入聲明。這是你的日期的數字表示。將該號碼作爲日期處理,將其轉換爲給定類型"NSDATE"

0

夫特4溶液:

在我的實施例I使用的便利方法HKQuery.predicateForSamples,這是爲樣品,其開始和結束日期落在指定時間間隔內的謂詞。

您需要閱讀的最後10 以下是如何從現在Date()

爲-10透水天

的startDate 10日得到一個日期是:Calendar.current.date(byAdding: .day, value: -10, to: Date())!

注意 :您可以使用您想要的下一個和上一個日期的日期,只需更改Date()。

結束日期爲:Date() - >(當前日期)

所以我斷言看起來像一個指定的時間間隔。

let predicate = HKQuery.predicateForSamples(
        withStart: startDate.beginningOfDay(), 
        end: endDate, 
        options: [.strictStartDate,.strictEndDate]) 

爲u可以在我的謂語我加入beginningOfDay()方法,這將讓我從00:00

beginningOfDay()方法描述開始日期見:

func beginningOfDay() -> Date { 
     let beginningOfDay = Calendar.current.startOfDay(for: self) 
     return beginningOfDay 
    } 

你也可以創建一個謂詞格式字符串來創建heathkitDoc中描述的等價謂詞。

let explicitTimeInterval = NSPredicate(format: "%K >= %@ AND %K < %@", 
             HKPredicateKeyPathEndDate, myStartDate, 
             HKPredicateKeyPathStartDate, myEndDate) 

希望能做到這一點。

相關問題