如何设置长度和纬度值(两者都显示app运行时)到全局常量?这些值目前是
String(format: "4.4f", latestLocation.coordinate.latitude)
和
String(format: "4.4f", latestLocation.coordinate.longitude)
我想让这些像userlatitude
和userlongitude
这样的全局常量可以在函数外部访问。我是否必须返回一些有意义的希望。
func locationManager(manager: CLLocationManager!,
didUpdateLocations locations: [AnyObject]!)
{
var latestLocation = locations.last as! CLLocation
latitude.text = String(format: "%.4f",
latestLocation.coordinate.latitude)
longitude.text = String(format: "%.4f",
latestLocation.coordinate.longitude)
}
答案 0 :(得分:1)
这样您就可以将地点存储到NSUserDefaults
:
//First Convert it to NSNumber.
let lat : NSNumber = NSNumber(double: Location.latitude)
let lng : NSNumber = NSNumber(double: Location.longitude)
//Store it into Dictionary
let locationDict = ["lat": lat, "lng": lng]
//Store that Dictionary into NSUserDefaults
NSUserDefaults.standardUserDefaults().setObject(locationDict, forKey: "Location")
之后,您可以通过这种方式访问它:
//Access that stored Values
let userLoc = NSUserDefaults.standardUserDefaults().objectForKey("Location") as! [String : NSNumber]
//Get user location from that Dictionary
let userLat = userLoc["lat"]
let userLng = userLoc["lng"]
var Annotation = MKPointAnnotation()
Annotation.coordinate.latitude = userLat as! CLLocationDegrees //Convert NSNumber to CLLocationDegrees
Annotation.coordinate.longitude = userLng as! CLLocationDegrees //Convert NSNumber to CLLocationDegrees
答案 1 :(得分:0)
定义您的变量以下导入语句。喜欢的东西,
import UIKit
let latitude = 4.0
// Do Stuff - This Variable access in Any class. Thanx Swift....
另一个解决方案是使用适当的密钥将您的值放在.plist/NSUser
默认值并访问每个类(您希望在何处使用)。
答案 2 :(得分:0)
一种解决方案可能是将值存储为NSUserDefaults,这样您就可以在需要时访问这些值。请尝试此链接以获取更多信息http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/