异步Swift调用数组

时间:2017-04-18 00:07:37

标签: arrays swift asynchronous firebase firebase-realtime-database

目前我正在尝试将值从firebase推送到一个note对象数组中 唯一的问题是由于Firebases异步性质,我无法让主线程等到获取功能完成。我在这个网站上看过很多答案,我已经阅读了Semaphores和Dispatch队列文档但是我无法让这个提取工作。看来这里的大多数人都试图使用我不是的桌面视图。

这是获取代码

func fetchUser(){


FIRDatabase.database().reference().child("notes").observe(.childAdded, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject] {
            let user = noteClass(dictionary: dictionary)
            self.coordinotes.append(user)
        }
    }, withCancel: nil)
} 

我删除了所有信号量并发送主要尝试,因为它们都没有工作。在我的视图中调用此函数加载。当我检查我的阵列的值时,我将它们推入“协调器”中。该值尚未放入,我得到一个越界错误。

其余代码

import UIKit
import MapKit
import CoreLocation
import Firebase
import FirebaseDatabase

struct PreferencesKeys{
    static let savedItems = "savedItems"
}




class ViewController: UIViewController, CLLocationManagerDelegate{

    let manager = CLLocationManager()
    var coordinotes:[noteClass] = Array()
    var latitude = Double()
    var noteTime = noteBrain()

    //Map
    @IBOutlet weak var map: MKMapView!


    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    {
        let location = locations[0]
        let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
        let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, noteTime.span)
        map.setRegion(region, animated: true)
        self.map.showsUserLocation = true
    }


    override func viewDidLoad()
    {
        super.viewDidLoad()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handleLogout))

        if FIRAuth.auth()?.currentUser?.uid == nil {
            perform(#selector(handleLogout), with: nil, afterDelay: 0)
        }
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()
        fetchUser()
        loadAllCoordinotes()
    }

    func handleLogout() {

        do {
            try FIRAuth.auth()?.signOut()
        } catch let logoutError {
            print(logoutError)
        }

        let loginController = LoginController()
        present(loginController, animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


func loadAllCoordinotes() {
    let length = coordinotes.count - 1
    map.addAnnotation(coordinotes[length])
}

1 个答案:

答案 0 :(得分:0)

func fetchUser(_ completion:@escaping ([noteClass] , _ success: Bool)-> Void){
    let coordinotes = [noteClass]() 

FIRDatabase.database().reference().child("notes").observe(.childAdded, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject] {
            let user = noteClass(dictionary: dictionary)
            coordinotes.append(user)
        }
        completion(coordinotes, true)
    }, withCancel: nil)

}

然后你在viewDidLoad中调用它:

  fetchUser { (coordinotes, success) in
            if success {
                self.coordinotes = coordinote
                self.loadAllCoordinotes()
            }
        }