ios - Swift 4 CLLocation 用户位置经度和纬度

标签 ios swift cllocationmanager cllocation userlocation

我转换为 Swift 4。我的 tableview 从 firebase 中提取数据并按与用户位置的距离组织它已停止工作。问题是我的用户位置一直显示为零。我听说最近有人因为转换而在 mapkit 上遇到麻烦,但不确定这是否属于同一类别。因此,“let userLocation = CLLocation(latitude: latitude!, longitude: longitude!)”这一行返回 nil。谢谢。

BreakPoint

override func viewDidLoad() {
    super.viewDidLoad()

    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true
    tableView.tableHeaderView = searchController.searchBar

    locationManager.delegate = self
    locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()
    locationManager.stopUpdatingLocation()
    locationManager.requestAlwaysAuthorization()

    getTableViewData()

    refresher = UIRefreshControl()
    refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
    refresher.addTarget(self, action: #selector(RegisteredLocations.handleRefresh(refreshControl:)), for: UIControlEvents.valueChanged)
    tableView.addSubview(refresher)
}

func getTableViewData() {
    Database.database().reference().child("Businesses").queryOrdered(byChild: "businessName").observe(.childAdded, with: { (snapshot) in

        let key = snapshot.key

        if(key == self.loggedInUser?.uid) {
            print("Same as logged in user, so don't show!")
        } else {
            if let locationValue = snapshot.value as? [String: AnyObject] {
                let lat = Double(locationValue["businessLatitude"] as! String)
                let long = Double(locationValue["businessLongitude"] as! String)
                let businessLocation = CLLocation(latitude: lat!, longitude: long!)

                let latitude = self.locationManager.location?.coordinate.latitude
                let longitude = self.locationManager.location?.coordinate.longitude
                let userLocation = CLLocation(latitude: latitude!, longitude: longitude!)

                let distanceInMeters: Double = userLocation.distance(from: businessLocation)
                let distanceInMiles: Double = distanceInMeters * 0.00062137
                let distanceLabelText = String(format: "%.2f miles away", distanceInMiles)

                var singleChildDictionary = locationValue
                singleChildDictionary["distanceLabelText"] = distanceLabelText as AnyObject
                singleChildDictionary["distanceInMiles"] = distanceInMiles as AnyObject
                self.usersArray.append(singleChildDictionary as NSDictionary)
                self.usersArray = self.usersArray.sorted {
                    !($0?["distanceInMiles"] as! Double > $1?["distanceInMiles"] as! Double)
                }

            }
            //insert the rows
            //self.followUsersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
            self.followUsersTableView.reloadData()
        }

    }) { (error) in
        print(error.localizedDescription)
    }

}

最佳答案

您在调用 locationManager.startUpdatingLocation() 后立即调用了 locationManager.stopUpdatingLocation()

这行不通,因为您需要时间来确定位置。在收到对 didUpdateLocations 委托(delegate)方法的调用之前,您不应使用位置。

如果您的目标是 iOS 9 及更高版本并且您只需要一个位置,那么您应该调用 requestLocation() 而不是 startUpdatingLocation() 但您仍然需要等待委托(delegate)方法的回调。

收到位置后,您就可以加载表格数据。

关于ios - Swift 4 CLLocation 用户位置经度和纬度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46480633/

相关文章:

iphone - iOS 6 map - 无法找到方向

ios - Objective-C ,iOS 7 - CLLocationManager : didUpdateLocations is being called only once

ios - 静态 TableViewCell 的 TextView

ios - 类型 'CMSampleBuffer' 的值没有成员 'imageBuffer'

ios - 使用 Handoff 和 Watchkit 将 iPhone 应用程序带到前台

swift - xcode8 。 Storyboard背景颜色不变

ios - 在 iOS 中获取准确位置

ios - 我如何从MGLConstantStyleValue迁移到NSExpression

ios - 核心数据与 iCloud。同步问题。 (MacOS 与 iOS - 冲突)

xcode - 快速连接到网络 smb 驱动器