Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 调用timeAgoSinceDate函数Swift_Ios_Swift - Fatal编程技术网

Ios 调用timeAgoSinceDate函数Swift

Ios 调用timeAgoSinceDate函数Swift,ios,swift,Ios,Swift,我是swift新手,我想知道调用此函数的正确方法。我还想知道使用此函数将字符串返回给视图控制器的正确方法。任何对新手的建议都会有帮助 解决方案: 新问题: 在为tableViewCell分配时间戳时,如何实现这一点,以便它能够在不引起问题的情况下频繁更新 import Foundation import Firebase import FirebaseDatabase import FirebaseStorage func UploadGeneralChatRoom(message : St

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

解决方案:

新问题:

在为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!
}
}//末级

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"
        }

    }
您需要一个NSDate对象才能传递到函数中,如下所示:

// Create a NSDate object using the current time
let now = NSDate()
let timeString = timeAgoSinceDate(date: now, numericDates: false)
按以下方式发送数据

按以下方式接收数据

更新你的方法


适用于所有在Swift 3.0中寻求工作时间间隔的用户


你到底想要什么?为什么要调用这个函数?原因是我们可以建议您。我正在尝试在tableView单元格上放置时间戳。每次打开视图时,在view上调用它将显示,以便它加载时间戳。每次更新表视图时,我都会给它一个快照。如果您要更新表视图,请在CoreData中的某个位置保留一份NSDate副本,以便您可以使用该值检索并发送给此函数。。所以时间戳是正确的。我可以知道tableview的数据源在哪里吗?我把它作为字符串发送到firebase,所以时间戳=刚刚。我应该这样上传吗?或者它应该是一个不同的值?你能告诉我我需要发送给firebase的值是多少吗。因为我刚刚发送了timeString值,所以我是否发送let now=NSDate此值?我该怎么做呢。如何初始化它并将其作为非字符串发送给firebase。每当您在FIRDatabase中插入条目时,都会向其发送一个带有名称时间戳的NSDate时间戳。然后像上面那样检索。。您将获得timeAgoSinceDatelet now=NSDate
// Create a NSDate object using the current time
let now = NSDate()
let timeString = timeAgoSinceDate(date: now, numericDates: false)
let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let nowString = dateFormatter.string(from: now)

ref.child("general_room").childByAutoId().setValue(["Usernam‌​e": username, "uid": userId, "Message" : message, "time_stamp" : nowString, "photo_url" : firebaseUserPhotoURL])
  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 ?? ""

    if let timeString = snapDict?["timeStamp"] as? String {

      let dateFormatter = DateFormatter()
      dateFormatter.dateFormat = "yyyy-MM-dd"
      let timeStampDate = dateFormatter.date(from: timeString)
      let timeStamp = timeAgoSinceDate(date: timeStampDate, numericDates: false)
      print("Time: " + timeStamp)
    }
    self.generalRoomDataArr.insert(postStruct(username: username, message: message, photoURL: firebaseUserPhotoURL, timeStamp: timeStamp), at: 0)
    self.tableView.reloadData()
func timeAgoSinceDate(date:Date, 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 as Date
let components = calendar.dateComponents(unitFlags, from: earliest as Date,  to: latest as Date)
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()
    }
}