Swift如何等待Async函数完成

时间:2015-12-18 18:20:41

标签: swift cllocation

我的困境:我将在下面的代码中骰子,但我的代码计划也是根据位置显示项目。当用户加载应用程序时,它应该显示它们周围的所有项目。我的问题是在我的视图中加载我调用startupdatinglocation后跟函数来查找我的项目。但是我找到我的项目的功能需要用户的位置,所以每次运行时该位置都是零。有没有办法,我可以等到找到一个位置然后做功能?

注 - 我已经尝试将find项功能放在didupdatelocation中,但是在用户加载应用程序时不会加载项。它只是留空了

var locManager = CLLocationManager()

var geocoder = CLGeocoder()

var placemarkLongitude = CLLocationDegrees()

var placemarkLatitude = CLLocationDegrees()

override func viewDidLoad() {
    super.viewDidLoad()
    // check if locations eabled
     print("I got here 1")
    if CLLocationManager.locationServicesEnabled() {
        self.locManager.delegate = self
        self.locManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locManager.requestWhenInUseAuthorization()
        self.locManager.startUpdatingLocation()
        print("I got here 2")
    }
    else {
        print ("Locations not enabled")
    }

    refresher = UIRefreshControl()
    refresher.attributedTitle = NSAttributedString(string: "Pull to Refresh")
    refresher.addTarget(self, action: "findItems", forControlEvents: UIControlEvents.ValueChanged)

    self.tableView.addSubview(refresher)

    findItems()

}

func locManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    print("Started Updating Location!")
    let userLocation: CLLocation = locations[0]
    _ = userLocation.coordinate.latitude
    _ = userLocation.coordinate.longitude
    print(locations)

}

1 个答案:

答案 0 :(得分:0)

当我需要先找到用户然后执行操作(更新UI /调用Web服务/等)时,这就是我通常所做的事情。

func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {

    //userLocated is a private bool property that will start on false (private let userLocated = false)
    if !userLocated {

        //Update the map region to center on the user with 0.02 span
        let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude), span: MKCoordinateSpanMake(0.02, 0.02))
        mapView.setRegion(region, animated: true)

        //Set the property to true as we already have a location for our user
        userLocated = true

        //Call Network API or do what you need here
        NetworkManager.sharedInstance.getItemsNerby(userLocation) //you can add a completion handler to then updateUI or do what you need with those items.
    }
}