Мне нужно взять данные из моей базы данных Firebase и поместить их в метки, но данные должны соответствовать моему заголовку ячейки tableView - PullRequest
0 голосов
/ 29 апреля 2019

Я создаю довольно простое приложение и столкнулся с проблемой. Сейчас у моего приложения есть домашний экран и табличное представление с названием события в каждой ячейке. Данные прекрасно загружаются из моей базы данных в мою ячейку, и когда вы нажимаете на ячейку, вы переходите к новому View Controller. Я хочу поместить конкретную информацию в каждую метку, которая соответствует названию моего мероприятия. Например, если в ячейке указано «STEM Leadership Confrence», когда я нажимаю на нее, я хочу, чтобы на трех метках был текст, который соответствует: дата, значение точки и период времени. Любая помощь будет оценена, спасибо. (База данных Swift 4 и Firebase RT)

import UIKit
import Firebase


var refa: DatabaseReference!

class TableViewController: UITableViewController {
    var posts = [eventStruct]()

    @IBOutlet weak var Tableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        refa = Database.database().reference()
        loadNews()
        Tableview?.delegate = self
        Tableview?.dataSource = self

    }
    struct eventStruct {
        let Name: String!
        let date: String!
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.performSegue(withIdentifier: "TableToSignUp", sender: self)


    }

    func loadNews() {
        refa.child("Events").queryOrderedByKey().observe(.childAdded, with: { (snapshot) in

            if let valueDictionary = snapshot.value as? [AnyHashable:String]
            {
                let Name = valueDictionary["Name"]
                let date = valueDictionary["date"]
                self.posts.insert(eventStruct(Name: Name, date: date), at: 0)
                self.Tableview.reloadData()


            }
        })
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return posts.count
    }

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

        let cell = Tableview.dequeueReusableCell(withIdentifier: "AllEventsCell", for: indexPath)

        //let label1 = cell.viewWithTag(1) as? UILabel
        cell.textLabel?.text = posts[indexPath.row].Name
        //let cell2 = Tableview.dequeueReusableCell(withIdentifier: "AllEventsCell", for: indexPath)



        return cell
}

}

класс ViewController: UIViewController, GIDSignInUIDelegate {

@IBOutlet weak var Nav: UINavigationBar!
@IBOutlet weak var NumOfParticipants: UITextField!
@IBOutlet weak var TimeFrame: UITextField!
@IBOutlet weak var EndDate: UITextField!
@IBOutlet weak var Points: UITextField!
@IBOutlet weak var Create: UIButton!
@IBOutlet weak var ViewAll: UIButton!
@IBOutlet weak var CreateEventButton: UIButton!
@IBOutlet weak var ViewMyEventsButton: UIButton!
@IBOutlet weak var Name: UITextField!
var ref: DatabaseReference?



override func viewDidLoad() {
    super.viewDidLoad()

    CreateEventButton?.layer.cornerRadius = 30
    CreateEventButton?.clipsToBounds = true
    Create?.layer.cornerRadius = 30
    Create?.clipsToBounds = true


    ViewMyEventsButton?.layer.cornerRadius = 30
    ViewMyEventsButton?.clipsToBounds = true


    ViewAll?.layer.cornerRadius = 30
    ViewAll?.clipsToBounds = true

    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().signIn()


    // Do any additional setup after loading the view.
}

@IBAction func CreateEvent(_ sender: Any) {
    let text: String = (Name.text)!
    let date: String = (EndDate.text)!
    let point: String = (Points.text)!
    let timeFrame: String = (TimeFrame.text)!
    let numOfpar: String = (NumOfParticipants.text)!
    ref = Database.database().reference()

    let now = Date()

    let formatter = DateFormatter()

    formatter.timeZone = TimeZone.current

    formatter.dateFormat = "yyyy-MM-dd"


    let dateString = formatter.string(from: now)

    let newUserData = ["Name": text, "date": date, "Point Value": point, "Time Frame": timeFrame, "Volunteers Needed": numOfpar, "Date Created": dateString] as [String: Any]



    ref?.child("Events").childByAutoId().updateChildValues(newUserData)




}


     //,; ["Amount of Points": point];["Date End": date]



}

класс AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {

let userDefault  = UserDefaults()

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
    if let error = error{
        print(error.localizedDescription)
        return


    }else{
        let userId = user.userID                  // For client-side use only!
        let idToken = user.authentication.idToken // Safe to send to the server
        let fullName = user.profile.name
        let givenName = user.profile.givenName
        let familyName = user.profile.familyName
        let email = user.profile.email
        let str = email
        let me = str?.count
        let int = (me!-9)
        let secondInt =  (me!-8)
        let XStr = str?.dropFirst(secondInt)
        let NewStr = str?.dropFirst(int)




        guard let authentication = user.authentication else{return}
        let crendential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
        Auth.auth().signInAndRetrieveData(with: crendential) {(result, error)in
            if error == nil {
                self.userDefault.set(true, forKey: "usersignedIn")
                self.userDefault.synchronize()


                 if(NewStr == "gmail.com"){

                    self.window?.rootViewController?.performSegue(withIdentifier: "TeacherSegue", sender: self)
                }

                else if(XStr == "aisd.net"){
                    self.window?.rootViewController?.performSegue(withIdentifier: "TeacherSegue", sender: self)


                }
            }else {
                //self.window?.rootViewController?.performSegue(withIdentifier: "Wegue", sender: self)

                print(error?.localizedDescription ?? "me")
            }
        }




    }


}
var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    // Override point for customization after application launch.
    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
    GIDSignIn.sharedInstance().delegate = self
    return true
}


@available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any])
    -> Bool {
        return GIDSignIn.sharedInstance().handle(url,
                                                 sourceApplication:options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
                                                 annotation: [:])
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    return GIDSignIn.sharedInstance().handle(url,
                                             sourceApplication: sourceApplication,
                                             annotation: annotation)
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}


Events-
      -LdK2x1kNMB6fBw0Oorn
      -LdLPGh-_SXIjM7DhjDV
      -LdPVnBYQtAtSOyZM1IR- 
          Date: "2019-04-28"
          Name:"STEM Leadership Confrence"
          Point Value: "12"
          Time Frame: "3-4"

1 Ответ

0 голосов
/ 29 апреля 2019

Вам необходимо передать информацию следующему UIViewController.

Во-первых, поместите всю необходимую вам информацию в ваш eventStruct и обновите инициализацию структуры внутри обратного вызова Firebase.

struct EventStruct {
   ...
   var timeFrame: String!
   var points: Int!
}

Если вы используете раскадровки, вам необходимо реализоватьtableView(_:didSelectRowAt:) метод и используйте segue для перехода к следующему виду.Эта ссылка поможет вам добавить идентификатор к вашему segue X-коду, где назначить идентификатор segue

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let detailToSend: EventStruct = posts[indexPath.row]
    performSegue(withIdentifier: "showDetailSegue", sender: detailToSend)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? ViewController, let detailToSend = sender as? EventStruct {            
        vc.detail = detailToSend
    }
}

Если вы используете код вида, вам просто нужен tableView(_:didSelectRowAt:)

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let detailToSend: EventStruct = posts[indexPath.row]
    let vc = ViewController()
    vc.detail = detailToSend
    self.present(vc, animated: true, completion: nil)
}

После этого в viewDidLoad() вашего ViewController назначьте информацию для меток.

TimeFrame.text = detail.timeFrame

Еще один совет, взгляните на быстрые лучшие практики, такие какhttps://github.com/raywenderlich/swift-style-guide или используйте SwiftLint в вашем проекте.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...