-2

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!

2 Answers2

0

Update Xcode to 8.3 or newer, there is a warning that you're printing an optional value instead of a normal one.

In your code you use DateComponents and all the fields are optional, like e.g. difference.hour. You're using ! before to extract the value to compare it, but it is not a good way as it crashes the app if the value isn't there.

What you should do is like this:

guard let hour = difference.hour,
      let minute = difference.minute, [...] else { return cell }
// below code using hour as not optional

in the method for every optional value to safely unwrap it.

Alistra
  • 5,177
  • 2
  • 30
  • 42
0

In Swift 3 all date components are optionals but you can safely unwrap all optionals which are specified in dateComponents(from:to:

I recommend to use local variables:

let difference = Calendar.current.dateComponents([.second, .minute, .hour, .day, .weekOfMonth], from: from, to: now)
let diffSec = difference.second!
let diffMin = difference.minute!
let diffHour = difference.hour!
let diffDay = difference.day!
let diffWeekOfMonth = difference.weekOfMonth!

if diffSec <= 0 {
    cell.postDate.text! = "now"
}
if diffSec > 0 && diffMin == 0 {
    cell.postDate.text! = "\(diffSec)s." // 12s.
}
if diffMin > 0 && diffHour == 0 {
    cell.postDate.text! = "\(diffMin)m."
}
if diffHour > 0 && diffDay == 0 {
    cell.postDate.text! = "\(diffHour)h."
}
if diffDay > 0 && diffWeekOfMonth == 0 {
    cell.postDate.text! = "\(diffDay)d."
}
if diffWeekOfMonth > 0 {
    cell.postDate.text! = "\(diffWeekOfMonth)w."
}

Nevertheless take a look at DateComponentsFormatter

vadian
  • 274,689
  • 30
  • 353
  • 361