gpt4 book ai didi

ios - 调用 timeAgoSinceDate 函数 Swift

转载 作者:行者123 更新时间:2023-11-28 15:48:30 26 4
gpt4 key购买 nike

我是 swift 的新手,我想知道调用此函数的正确方法。我还想知道使用此函数将字符串返回给 View Controller 的正确方法。对新手的任何建议都会有所帮助。

解决方案:

let now = NSDate()
let timeString = timeAgoSinceDate(date: now, numericDates: false)

新问题:

如何在为 tableViewCell 分配时间戳时实现这一点,以便它频繁更新而不会引起问题

import Foundation
import Firebase
import FirebaseDatabase
import FirebaseStorage


func UploadGeneralChatRoom(message : String) {

//Firebase Initialization
var ref: FIRDatabaseReference!
//var storage: FIRStorageReference!
let userID = FIRAuth.auth()?.currentUser?.uid
ref = FIRDatabase.database().reference()
//storage = FIRStorage.storage().reference()


//Get Data from database resend to database
if let userId = userID {
ref.child("Users").child(userID!).observeSingleEvent(of: .value, with: {(snapshot) in

let snapDict = snapshot.value as? NSDictionary
let username = snapDict?["Username"] as? String ?? ""
let firebaseUserPhotoURL = snapDict?["photo_url"] as? String ?? ""

let now = NSDate()

ref.child("general_room").childByAutoId().setValue(["Username": username, "uid": userId, "Message" : message, "time_stamp" : now, "photo_url" : firebaseUserPhotoURL])



// ref.child("general_room").child("chat").child(userID!).childByAutoId().setValue(["Username": username, "uid": userID!, "Message" : message, "photo_url" : firebaseUserPhotoURL])







})

}

}//END func



import UIKit
import Foundation
import Firebase
import FirebaseDatabase
import FirebaseStorage
import AlamofireImage
import Alamofire

struct postStruct {
let username : String!
let message : String!
let photoURL : String!
let timeStamp: String!
}



class GeneralChatroom: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {

@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var tableView: UITableView!
var generalRoomDataArr = [postStruct]()


override func viewDidLoad() {
super.viewDidLoad()


//TableView Cell word wrap (Dynamic Text)
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.estimatedRowHeight = 78
self.tableView.rowHeight = UITableViewAutomaticDimension



let ref = FIRDatabase.database().reference()
//let userID = FIRAuth.auth()?.currentUser?.uid


ref.child("general_room").queryOrderedByKey().observe(.childAdded, with: {snapshot in

let snapDict = snapshot.value as? NSDictionary
let username = snapDict?["Username"] as? String ?? ""
let message = snapDict?["Message"] as? String ?? ""
let firebaseUserPhotoURL = snapDict?["photo_url"] as? String ?? ""

//Time Stamp string
let now = NSDate()
let timeString = timeAgoSinceDate(date: now, numericDates: false)
print("Time: " + timeString)

self.generalRoomDataArr.insert(postStruct(username: username, message: message, photoURL: firebaseUserPhotoURL, timeStamp: timeString), at: 0)
self.tableView.reloadData()



})

}


@IBAction func backButtonPressed(_ sender: UIButton) {
self.performSegue(withIdentifier: "BackToRoom", sender: nil)
}


//Message Send button is pressed data uploaded to firebase
@IBAction func sendButtonPressed(_ sender: UIButton) {



//If a character exists will be uploaded to firebase
if ((messageTextField.text?.characters.count)! > 0) {

let message : String = self.messageTextField.text!
UploadGeneralChatRoom(message: message) //upload to general_room
self.messageTextField.text = nil
messageTextField.resignFirstResponder()//Quit keyboard

self.tableView.reloadData() //Reload tableView
//UploadUserData() //Update Rank in database

}


}








func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return generalRoomDataArr.count // your number of cell here
}




func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {




let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

//Set username label to display username
let usernameLabel = cell?.viewWithTag(1) as! UILabel
usernameLabel.text = generalRoomDataArr[indexPath.row].username

//Set message label to display message
let messageLabel = cell?.viewWithTag(2) as! UILabel
messageLabel.text = generalRoomDataArr[indexPath.row].message
messageLabel.numberOfLines = 0

//initialize UI Profile Image
let imageView = cell?.viewWithTag(3) as! UIImageView

//Make Porfile Image Cirlce
imageView.layer.cornerRadius = imageView.frame.size.width/2
imageView.clipsToBounds = true

//Set timeStampLabel to current time AGO
let timeStampLabel = cell?.viewWithTag(4) as! UILabel
timeStampLabel.text = generalRoomDataArr[indexPath.row].timeStamp

//Loading and change of Usesrs profile image on chat cell
let userProfileChatImage = generalRoomDataArr[indexPath.row].photoURL

//Load profile image(on cell) with URL & Alamofire Library
let downloadURL = NSURL(string: userProfileChatImage!)
imageView.af_setImage(withURL: downloadURL as! URL)

// your cell coding
return cell!
}

}//结束类(class)

func timeAgoSinceDate(date:NSDate, numericDates:Bool) -> String {
let calendar = NSCalendar.current
let unitFlags: Set<Calendar.Component> = [.minute, .hour, .day, .weekOfYear, .month, .year, .second]
let now = NSDate()
let earliest = now.earlierDate(date as Date)
let latest = (earliest == now as Date) ? date : now
let components = calendar.dateComponents(unitFlags, from: earliest as Date, to: latest as Date)

if (components.year! >= 2) {
return "\(components.year!) years ago"
} else if (components.year! >= 1){
if (numericDates){
return "1 year ago"
} else {
return "Last year"
}
} else if (components.month! >= 2) {
return "\(components.month!) months ago"
} else if (components.month! >= 1){
if (numericDates){
return "1 month ago"
} else {
return "Last month"
}
} else if (components.weekOfYear! >= 2) {
return "\(components.weekOfYear!) weeks ago"
} else if (components.weekOfYear! >= 1){
if (numericDates){
return "1 week ago"
} else {
return "Last week"
}
} else if (components.day! >= 2) {
return "\(components.day!) days ago"
} else if (components.day! >= 1){
if (numericDates){
return "1 day ago"
} else {
return "Yesterday"
}
} else if (components.hour! >= 2) {
return "\(components.hour!) hours ago"
} else if (components.hour! >= 1){
if (numericDates){
return "1 hour ago"
} else {
return "An hour ago"
}
} else if (components.minute! >= 2) {
return "\(components.minute!) minutes ago"
} else if (components.minute! >= 1){
if (numericDates){
return "1 minute ago"
} else {
return "A minute ago"
}
} else if (components.second! >= 3) {
return "\(components.second!) seconds ago"
} else {
return "Just now"
}

}

最佳答案

致所有在 Swift 3.0 中寻找工作 timeAgoSinceDate 函数的人

func timeAgoSinceDate(date:Date, numericDates:Bool) -> String {
let calendar = NSCalendar.current
let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfYear, .month, .year]
let now = NSDate()
let components = (calendar as NSCalendar).components(unitFlags, from: date, to: now as Date, options: [])

if (components.year! >= 2) {
return "\(components.year!)" + " years ago".localized()
} else if (components.year! >= 1){
if (numericDates){
return "1 year ago".localized()
} else {
return "Last year".localized()
}
} else if (components.month! >= 2) {
return "\(components.month!)" + " months ago".localized()
} else if (components.month! >= 1){
if (numericDates){
return "1 month ago".localized()
} else {
return "Last month".localized()
}
} else if (components.weekOfYear! >= 2) {
return "\(components.weekOfYear!)" + " weeks ago".localized()
} else if (components.weekOfYear! >= 1){
if (numericDates){
return "1 week ago".localized()
} else {
return "Last week".localized()
}
} else if (components.day! >= 2) {
return "\(components.day!)" + " days ago".localized()
} else if (components.day! >= 1){
if (numericDates){
return "1 day ago".localized()
} else {
return "Yesterday".localized()
}
} else if (components.hour! >= 2) {
return "\(components.hour!)" + " hours ago".localized()
} else if (components.hour! >= 1){
if (numericDates){
return "1 hour ago".localized()
} else {
return "An hour ago".localized()
}
} else if (components.minute! >= 2) {
return "\(components.minute!)" + " minutes ago".localized()
} else if (components.minute! >= 1){
if (numericDates){
return "1 minute ago".localized()
} else {
return "A minute ago".localized()
}
} else if (components.second! >= 3) {
return "\(components.second!)" + " seconds ago".localized()
} else {
return "Just now".localized()
}
}

关于ios - 调用 timeAgoSinceDate 函数 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42618584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com