So I have this code that takes the date of when a time was posted and converts it to something like "5h" or "1d" ago. However, it is displaying in my application as something like this - Optional(1)h.
Here is the code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "admincell", for: indexPath) as! AdminHomeCell
let post = activities[indexPath.row]
print(post["path"])
//let image = images[indexPath.row]
//let imaged = post["path"] as! String
//let image = URL(string: imaged)
let username = post["username"] as? String
let title = post["title"] as? String
let date = post["date"] as! String
let description = post["text"] as? String
let location = post["location"] as? String
let dateFormater = DateFormatter()
dateFormater.dateFormat = "yyyy-MM-dd-HH:mm:ss"
let newDate = dateFormater.date(from: date)!
let from = newDate
let now = Date()
let components : NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfMonth]
let difference = (Calendar.current as NSCalendar).components(components, from: from, to: now, options: [])
if difference.second! <= 0 {
cell.postDate.text! = "now"
}
if difference.second! > 0 && difference.minute! == 0 {
cell.postDate.text! = "\(difference.second)s." // 12s.
}
if difference.minute! > 0 && difference.hour! == 0 {
cell.postDate.text! = "\(difference.minute)m."
}
if difference.hour! > 0 && difference.day! == 0 {
cell.postDate.text! = "\(difference.hour)h."
}
if difference.day! > 0 && difference.weekOfMonth! == 0 {
cell.postDate.text! = "\(difference.day)d."
}
if difference.weekOfMonth! > 0 {
cell.postDate.text! = "\(difference.weekOfMonth)w."
}
/*
let session = URLSession(configuration: .default)
let downloadPicTask = session.dataTask(with: image!) {
(data, response, error) in
if let e = error {
print("Error downloading image: \(e)")
} else {
if let res = response as? HTTPURLResponse {
if let image = data {
let pic = UIImage(data: image)
cell.postImage.image = pic
} else{
print("couldn't get image: image is nil")
}
} else {
print("Couldn't get response code")
}
}
}
*/
cell.postTitle.text = title
cell.postUser.text = username
cell.postDescription.text = description
cell.postLocation.text = location
cell.postDate.text = date
cell.postDescription.lineBreakMode = .byWordWrapping // or NSLineBreakMode.ByWordWrapping
cell.postDescription.numberOfLines = 0
//downloadPicTask.resume()
return cell
}
If there is anything I should change to make it simply display "1h", please let me know! Thanks!