需要使用Parse.com按日期排序iOS,但我需要根据特定人的下一个生日订购它们。我试图在当前或明年添加日期和月份,这有帮助,但这将是一个手动过程,任何建议以自动方式执行此操作。
作为旁注,我想在swift中实现它
提前全部谢谢。
答案 0 :(得分:2)
确切的代码将取决于您的个人设置(我可以想象您已经创建了PFObject
或类似的子类),但尝试使用以下代码进行试验。我还创建了另一个名为filterFriendsAfterBirthdays
的函数,对于阅读这篇文章的人来说可能很有用。
//
// ViewController.swift
// ParseFun
//
// Created by Stefan Veis Pennerup on 20/06/15.
// Copyright (c) 2015 Kumuluzz. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
createDummyData()
queryForFriends() {
println("Unsorted birthdays: \($0)")
println("Sorted birthdays: \(self.filterFriendsAfterBirthdays($0))")
println("Closets upcoming birthday: \(self.filterFriendsBasedOnClosetsUpcomingBirthday($0))")
}
}
func createDummyData() {
for var i = 0; i < 25; i++ {
let myFriend = PFObject(className: "Friends")
let interval = Double(arc4random_uniform(UInt32.max))
myFriend["birthday"] = NSDate(timeIntervalSince1970: interval)
myFriend.saveInBackground()
}
}
func queryForFriends(completionHandler: ([PFObject]) -> ()) {
let friendsQuery = PFQuery(className: "Friends")
friendsQuery.findObjectsInBackgroundWithBlock { (result, error) in
if (error != nil) { return }
let pfArray = result as! [PFObject]
completionHandler(pfArray)
}
}
func filterFriendsAfterBirthdays(friends: [PFObject]) -> [PFObject] {
return friends.sorted {
return ($0["birthday"] as! NSDate).compare($1["birthday"] as! NSDate) == .OrderedAscending
}
}
func filterFriendsBasedOnClosetsUpcomingBirthday(friends: [PFObject]) -> [PFObject] {
let cal = NSCalendar.currentCalendar()
// Specifies the day unit
let dayUnit: NSCalendarUnit = .CalendarUnitDay
// Gets todays year
let today = NSDate()
let yearUnit: NSCalendarUnit = .CalendarUnitYear
let yearToday = cal.components(yearUnit, fromDate: today)
// Combined days and year units
let combinedUnits: NSCalendarUnit = .CalendarUnitYear | .CalendarUnitDay
return friends.sorted {
// Gets the birthday components since today
// Also uses the year unit to ensure that the day will be between -365 and 365
let birth1Components = cal.components(combinedUnits, fromDate: today, toDate: ($0["birthday"] as! NSDate), options: nil)
let birth2Components = cal.components(combinedUnits, fromDate: today, toDate: ($1["birthday"] as! NSDate), options: nil)
// Updates the days to a positive integer
if (birth1Components.day < 0) { birth1Components.day += 365 }
if (birth2Components.day < 0) { birth2Components.day += 365 }
return birth1Components.day <= birth2Components.day
}
}
}