このコードでは、時刻が送信された日付が "5h"や "1d"のようなものに変換されます。しかし、私のアプリケーションでは、このようなものとして表示されています - オプション(1)h。ここでSwift 3 - 値が文字列の場合に任意の値を受け取る
コードです:私は、それは単に「1H」を表示するために変更すべきものがあれば
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
}
、私に知らせてください!ありがとう!
車輪を改造するのではなく、 'DateComponentsFormatter'を使用してみませんか? – rmaddy