我遇到了将从函数调用返回的字符串分配给UILabel
文本的情况。但是,UILabel
带有空值。如果我要分配一个静态字符串即。 “正在测试”直接作用于UILabel
。在函数中,我可以打印返回值
import Foundation
import Firebase
import UIKit
class checkLocation{
var items = [addedItems]()
func getLocationOfItem(textFieldText: (String)) -> String{
let itemLet = addedItems()
var location = ""
Database.database().reference().child("item").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject]{
//itemLet.setValuesForKeys(dictionary)
itemLet.itemName = dictionary["itemName"] as? String
itemLet.itemLocation = dictionary["itemLocation"] as? String
itemLet.itemImageUrl = dictionary["itemImageUrl"] as? String
itemLet.itemTS = dictionary["itemTS"] as? String
itemLet.id = dictionary["id"] as? String
if(textFieldText == itemLet.itemName){
location = itemLet.itemLocation!
print(location)
}
}
}, withCancel: nil)
return location
}
}
呼叫程序
import UIKit
import Firebase
class checkLocationViewController: ViewController {
@IBOutlet weak var itemNameInLctn: UITextField!
@IBOutlet weak var itemLocationLbl: UILabel!
var items = [addedItems]()
var strLocation = "";
override func viewDidLoad() {
super.viewDidLoad()
refItems = Database.database().reference().child("item")
}
@IBAction func getLocation(_ sender: UIButton) {
self.strLocation = checkLocation().getLocationOfItem(textFieldText: itemNameInLctn.text!)
itemLocationLbl.text = strLocation
//itemLocationLbl.text = strLocation
//print(itemNameInLctn.text)
}
}
有帮助吗?
func getLocationOfItem(textFieldText: (String)) -> String
正确返回初始值为“”的location
。
您面临的问题是,您正在同步功能调用中从firebase调用异步任务。
您可以通过以下更改来重构方法调用以异步返回所需的字符串:
func getLocationOfItem(textFieldText: String, completion: @escaping (_ itemLocation: String?) -> Void){
let itemLet = addedItems()
Database.database().reference().child("item").observe(.childAdded, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: AnyObject] else {
return completion(nil)
}
itemLet.itemName = dictionary["itemName"] as? String
itemLet.itemLocation = dictionary["itemLocation"] as? String
itemLet.itemImageUrl = dictionary["itemImageUrl"] as? String
itemLet.itemTS = dictionary["itemTS"] as? String
itemLet.id = dictionary["id"] as? String
if(textFieldText == itemLet.itemName){
completion(itemLet.itemLocation)
} else {
completion(nil)
}
}, withCancel: nil)
}
/// Usage
@IBAction func getLocation(_ sender: UIButton) {
guard let itemNameInLocation = itemNameInLctn.text else { return }
getLocationOfItem(textFieldText: itemNameInLocation) { [weak self] (itemLocation) in
self?.strLocation = itemLocation
self?.itemLocationLbl.text = itemLocation
}
}
注意:
请注意,每次在Firebase数据库的item
路径下添加值时,都会调用完成处理程序。在这种情况下,我强烈建议您进一步重构,以使用firebase提供的observeSingleEvent
。
请参阅下面的链接以获取有关所述方法的文档:
https://firebase.google.com/docs/database/ios/read-and-write#read_data_once
如果这是您的意图,那么它是最佳选择。