方法适用于模拟器但在设备上崩溃。 Swift 2.2

时间:2016-08-26 01:35:46

标签: ios iphone swift2 nsdate nsdateformatter

我正在尝试创建一个方法,该方法将返回自请求发出以来经过的时间量。此方法接受一个名为requestTime的参数。由于时间可以在24小时前:"08/25/16, 14:34"或12小时前:"08/25/16, 2:34 PM",因此该方法会考虑所有这些变量并正确处理它们。现在问题是:这个方法适用于Playgound和模拟器,但不能在我的设备上运行它。 (见下图)

func calculateTimeSinceRequestWasMade(requestTime:String) -> String{

//Empty variable for 24 hour format
var dateIn24HrFormat = ""

if(requestTime.containsString("AM") || requestTime.containsString("PM")){

    //If request time was in 12 hr format we convert it into 24hr
    let dateFormatter1 = NSDateFormatter()
    dateFormatter1.dateFormat = "MM/dd/yy, h:mm a"
    let date = dateFormatter1.dateFromString(requestTime)
    dateFormatter1.dateFormat = "MM/dd/yy, HH:mm"
    dateIn24HrFormat = dateFormatter1.stringFromDate(date!)

}else{
    //If it was already 24hr we just assign it to our 24hr variable
    dateIn24HrFormat = requestTime
}


//Create a time object of the current date in the desired format
let today = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "MM/dd/yy, HH:mm"
let currentFormattedTime = formatter.stringFromDate(today)

//Create a formatter
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM/dd/yy, HH:mm"
let dateAsString = dateIn24HrFormat

//Assign both variable with nice names
let postTime = dateFormatter.dateFromString(dateAsString)
let currentTime = dateFormatter.dateFromString(currentFormattedTime)


//Compare the time of both posts and the results is divided by 60, so the result is in minutes
let timeSincePost = (currentTime!.timeIntervalSinceDate(postTime!)/60)

if(timeSincePost < 60){
    return ("\(Int(timeSincePost))m")
}else{
    return ("\(Int(timeSincePost/60))h")
}

}

如您所见,在此playground文件中,该方法适用于24小时和12小时格式。两个方法调用都返回“6h”,这意味着该帖子是在6小时前发布的。 Screenshot 1: Playgrounds

然而,每当我在我的设备上运行此方法时,它根本不起作用。它崩溃,因为它强行解开零。如果我在内置的模拟器上运行它,它可以工作,但每当我在我的实际设备中运行它时它不会。 Screenshot 2: Running on device

这是我遇到的最奇怪的错误...我正在运行的设备是运行9.0.2的iPhone 5s。如果可以,请帮助我!

0 个答案:

没有答案