2017-07-07 47 views
0

我正在嘗試使用Firebase做兩個認證級別的iOS應用。 第二個驗證必須通過在文本字段中插入代碼巫婆位於數據庫中進行驗證。如何使用firebase在swift代碼上創建搜索字段?

json root

// 
// AccessoTerzoLivello.swift 
// amesci 
// 
// Created by Gianluca Caliendo on 07/07/17. 
// Copyright © 2017 Amesci. All rights reserved. 
// 

import UIKit 
import Firebase 

class AccessoTerzoLivello: UIViewController { 

    @IBOutlet weak var CodiceVolontarioTxt: UITextField! 

    @IBAction func Accedi(_ sender: UIButton) { 

    var rootRef: DatabaseReference! 

    rootRef = Database.database().reference() 

    var conditionalRef = rootRef.child("SchedaVolontari") 

    conditionalRef.observe(.value) {(snap: DataSnapshot) in } 

    if self.CodiceVolontarioTxt.text = snap 

    } 
    else { 
     let alert = UIAlertController(title: "Errore", message: "Codice volontario non valido", preferredStyle: UIAlertControllerStyle.alert) 
     alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: nil)) 

     self.present(alert, animated: true, completion: nil) 
    } 
    } 
} 
+0

歡迎來到StackOverflow。查看SO的[如何使用](https://stackoverflow.com/help/how-to-ask)部分,並更新您的問題。還提供了迄今爲止嘗試的細節。 –

回答

0

您是在正確的道路。沒有您的線路有問題:

if self.CodiceVolontarioTxt.text = snap

Snap是保持你的代碼的字典,你不能把它比作你的文字輸入。首先你必須從中得到所有的代碼。

這是一些代碼。我沒有測試過,但它會給你一個想法。用你的完成塊代替if else語句:

// This is empty array which will contain all the codes 
var codesArray: NSMutableArray = [] 

// Get all the children from snapshot you got back from Firebase 
let snapshotChildren = snap.children 

// Loop over all children (code) in Firebase 
while let child = snapshotChildren.nextObject() as? FIRDataSnapshot { 
    // Get code node key and save it to codes array 
    codes.add(child.key) 
} 

// Compare if inserted text matches any code from database 
if codesArray.contains(self.CodiceVolontarioTxt.text) { 
    print("Code exists in Firebase") 
} else { 
    print("Code does not exist in Firebase") 
} 
+0

謝謝你的幫助ZassX,代碼有兩個問題:類型NSMutableArray的值沒有成員'append' –

+0

@GianlucaCaliendo對不起,我試着用codesArray.add(child.getKey())。我已經更新了上面的答案。 – ZassX

+0

還有一個問題:「類型'FIRDataSnapshot'的值沒有成員'getKey'」 –

相關問題