1)摇手机时我读取文件,保存时保存日期它,如果24小时过去了,我可以再次摇晃并接收有关UILabel的信息,如果没有,它将继续等待。
2)但是,现在我需要在第一次打开视图时无需用户执行任何操作即可读取文件,并且该文本将自动显示在UILabel中并保存发生日期。当用户再次打开视图时,我必须比较日期,如果是昨天,则再次自动读取文件,如果没有,则没有任何变化
现在,第一种情况有以下代码。它需要在第二个下传输,但是我不知道如何!
extension Date {
func isOutdated(forHours hours: Int) -> Bool {
let plusHours = self.dateByAddingHours(hours)
return plusHours.lessThan(Date())
}
func dateByAddingHours(_ dHours: NSInteger) -> Date {
let aTimeInterval = self.timeIntervalSinceReferenceDate + Double(3600) * Double(dHours)
let newDate = Date(timeIntervalSinceReferenceDate: aTimeInterval)
return newDate
}
func lessThan(_ date: Date) -> Bool {
return self.compare(date) == ComparisonResult.orderedAscending
}}
此代码在ViewController类中]
if (motion == .motionShake) {
makeActionIfNeeded()
}
}
func actionAfterShake(){
let key = "toDateLabel"
UserDefaults.standard.set(Date(), forKey: key)
let dateLabel = UserDefaults.standard.object(forKey: key) as! Date
let df = DateFormatter()
df.dateFormat = "dd/M/yyyy"
toDateOutlet.text = df.string(from: dateLabel)
let path = Bundle.main.path(forResource: "predict", ofType: "txt")
let url = URL(fileURLWithPath: path!)
let contentString = try! NSString(contentsOf: url, encoding: String.Encoding.utf8.rawValue)
let msgString = contentString.components(separatedBy: ".").randomElement()!.replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: "\n", with: "")
self.predictLabel.text = msgString
saveDate()
}
func saveDate()
{ let key = "toDate"
UserDefaults.standard.set(Date(), forKey: key)
}
func makeActionIfNeeded() {
let key = "toDate"
let date = UserDefaults.standard.object(forKey: key) as? Date
if date?.isOutdated(forHours: 24) ?? true{
actionAfterShake()
savePredict()
}
}
1)我在摇动手机时读取了文件,在保存时保存了日期,如果过了24小时,我可以再次摇动并接收UILabel上的信息,如果没有继续等待。 2)...
我认为第二种情况是不可能的。 iOS不允许您安排在特定时间唤醒应用程序。您可以在特定时间从服务器向应用发送推送通知,但是如果该应用已完全终止,则该通知将不起作用。