在最近的一天从数组中获取项目

时间:2017-08-16 19:28:15

标签: ios swift firebase firebase-realtime-database nsdate

我以这种格式向日期Firebase添加项目:

// retrieve data from Firebase to the View
var dateToCompare: String?
var array: [Word] = []

func getAllMessagesSent(snapshot: [Word]) {
    int = snapshot.count - 1
    array = snapshot

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MM/dd/yyyy"
    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

    // get the nearest item's date and convert it to Date
    dateToCompare = array[0].fullDate
    let formattedDateToCompare = dateFormatter.date(from: dateToCompare!)

    // make array of dates
    var dateArray = [NSDate]()
    var numberOfWordsThisDay = 1

    // formatting all dates in the array
    for i in 0..<array.count {
        let date1 = dateFormatter.date(from:  array[i].fullDate)
        dateArray.append(date1! as NSDate)
    }

    // comparing and in case of cussces increase the number
    for i in 1..<array.count {
        if Calendar.current.compare(formattedDateToCompare!, to: dateArray[i] as Date, toGranularity: .day) == .orderedSame {
            numberOfWordsThisDay += 1
        }
    }
    self.numOfWords.placeholder = "From \(numberOfWordsThisDay) to \(array.count)"
}

所以,我的Firebase for Date看起来像这样:

CryptographicException

然后,我在另一个ViewController中检索这些数据并将其添加到数组中:

image_ID

问题:

如何从最近的一天从数组中检索项目?如果今天是8月16日,我应该获得最近一天的所有项目(例如,8月12日的8个项目,如果这个日期是最后一个)。我是否应该改变向Firebase添加日期以实现此目的的方式?

修改

我通过将数组中的最后一个日期与所有其他日期进行比较来实现此目的:

SELECT pro.id
 , pro.featured
 , pro.price_per_night
 , pro.meta_title
 , img.image

它可以工作,但它绝对不是有效的解决方案,因为我循环了两个巨大的数组。是否可以改进我的代码?谢谢!

0 个答案:

没有答案
相关问题