Swift将DatePicker Date更改为Firebase

时间:2017-01-31 21:18:35

标签: swift firebase datepicker firebase-realtime-database

在我的应用中,您点击一个按钮,活动名称和活动位置就会添加到Firebase中。我还想在Firebase中添加您将要执行活动的选定时间。为此,我创建了一个DatePicker,在单击按钮时弹出,我还设法将其转换为字符串并上传到Firebase。

我遇到的问题是它上传到Firebase的时间总是当前时间,我是否正确地说我需要向DatePicker添加一个动作,以便允许上传所选时间?如果是这样,我该怎么做?

 func handleAddAgenda(){

    var datePicker: UIDatePicker = UIDatePicker()
    datePicker.datePickerMode = UIDatePickerMode.DateAndTime
    //datePicker.addTarget(self, action: #selector(dateChanged), forControlEvents: UIControlEvents.ValueChanged)
    datePicker.frame = CGRectMake(0, 0, 250, 460)
    datePicker.backgroundColor = UIColor.whiteColor()
    addSubview(datePicker)

    class ActDate: NSObject {
        var date: String?
    }

    var actDate: ActDate?

    if actDate == nil {
        actDate = ActDate()
    }


    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "hh:mm a"
    actDate?.date = dateFormatter.stringFromDate(datePicker.date)
    print(datePicker.date)

    let userID = FIRAuth.auth()?.currentUser?.uid
    let ref = FIRDatabase.database().reference().child("users").child(userID!).child("Agenda")
    let childRef = ref.childByAutoId()
    let values = ["activity": activityName.text!, "location": distance.text!, "date": actDate!.date!]
    childRef.updateChildValues(values)
}

1 个答案:

答案 0 :(得分:1)

是的,您需要添加一些操作方法来在选择datePicker日期时更新值。只有当你将日期选择器作为整个类的属性才能在新方法中获取datePicker.date时,这只会起作用。

viewDidLoad中的类似内容:

datePicker.datePickerMode = UIDatePickerMode.DateAndTime
datePicker.frame = CGRectMake(0, 0, 250, 460)
datePicker.backgroundColor = UIColor.whiteColor()
myDatePicker.addTarget(self, action: #selector(dateChanged), for: .valueChanged)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm a"
actDate?.date = dateFormatter.stringFromDate(datePicker.date)

然后,您可以将handleAgenda简化为:

func handleAddAgenda(){
    addSubview(datePicker)
    print(datePicker.date)
}

最后在方法中进行FireBase更新:

func dateChanged() {
     if let userID = FIRAuth.auth()?.currentUser?.uid {
         let ref = FIRDatabase.database().reference().child("users").child(userID).child("Agenda")
         let childRef = ref.childByAutoId()
         if let activityName = activityName.text, let distance = distance.text, let date = datePicker.date {
             let values = ["activity": activityName, "location": distance, "date": date]
             childRef.updateChildValues(values)
        }
    }
}