新手紧急求帮助,在viewDidLoad中得不到定位坐标和城市

qq_38779650 2017-05-14 10:32:58
下面代码中viewDidLoad里面
print("\(self.currentLocation)")
print("\(self.currentCity)")
结果始终是nil

locationManager里面
print("\(self.currentLocation)")
print("\(self.currentCity)")
结果是
Optional(<+31.00000000,+120.60000000> +/- 5.00m (speed -1.00 mps / course -1.00) @ 5/14/17, 2:00:16 AM China Standard Time)
Optional("Suzhou")

怎么在viewDidLoad中取得坐标和城市



import UIKit
import CoreLocation

class WeatherCityVC: UIViewController,CLLocationManagerDelegate,URLSessionDelegate {

var locationManager:CLLocationManager!
var geocoder:CLGeocoder!
var currentLocation:CLLocation!
var currentCity:String!


func locate() {
if !CLLocationManager.locationServicesEnabled(){
print("定位失败")
return
}
locationManager = CLLocationManager()
locationManager.delegate = self

locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 500
locationManager.startUpdatingLocation()
}



override func viewDidLoad() {
super.viewDidLoad()

locate()
print("\(self.currentLocation)")
print("\(self.currentCity)")

}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


//MARK: - CoreLocation delegate

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error")
}


func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count > 0 {
manager.stopUpdatingLocation()
self.currentLocation = locations.last

self.geocoder = CLGeocoder()
self.geocoder.reverseGeocodeLocation(self.currentLocation!, completionHandler:{(placeMarks,error) -> Void in
let pm = placeMarks
self.currentCity = pm?.first?.locality
print("\(self.currentLocation)")
print("\(self.currentCity)")
})
}

}
...全文
674 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

1,420

社区成员

发帖
与我相关
我的任务
社区描述
Swift,苹果于2014年WWDC(苹果开发者大会)发布的新开发语言,可与Objective-C共同运行于MAC OS和iOS平台,用于搭建基于苹果平台的应用程序。
swift 技术论坛(原bbs)
社区管理员
  • Swift
  • 网罗开发
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧