結論 ライブラリSwiftDateが秀逸
private func checkPoints(callback: @escaping ((Int?, String?)->Void)) {
//userREFはviewwillAppearでFirebase Authから documentをget下記参照
userREF.collection(DIARY_REF).order(by: CREATED_AT, descending: true).limit(toLast: 2).getDocuments { (snap, error) in
if let error = error?.localizedDescription {
callback(0, error)
return
}
guard let dateStr = snap?.documents.compactMap({ $0[CREATED_AT] as? Timestamp }), dateStr.count == 2 else {
callback(0,nil)
return
}
//dateValueでNSDate型へキャスト
let days = dateStr.compactMap({$0.dateValue()})
let firstDay = days[0]
let secondDay = days[1]
//2つ目のdateに 1日プラスする処理も簡単
if (secondDay + 1.days).compare(toDate: firstDay, granularity: .day) == ComparisonResult.orderedSame {
callback(10, nil)
}else{
callback(0,nil)
}
}
}
Timestamp はFirebaseの日付の型
//trailing clousureを利用
checkPoints { (point, err) in
if let err = err { print(err) }
//ここへcallbackが返却される
guard let point = point else { return }
User.loggedIn?.points += point
User.loggedIn?.save()
self.uploadPhoto() { imgRef in self.saveDiary(photoRef: imgRef) }
}
//メンバ変数
let db = Firestore.firestore()
private var userId:String?
var userREF: DocumentReference!
override func viewWillAppear(_ animated: Bool) {
userId = Auth.auth().currentUser!.uid
userREF = db.collection(USER_REF).document(userId!)
}