Swift - 在plist

时间:2015-12-06 20:20:55

标签: ios arrays swift dictionary plist

我正在创建一个简单的应用程序,搜索包含地理修复的大型plist,以及相应的lat和long坐标。计划是能够在搜索框中搜索这些修复,然后按一个按钮来定位一个地图视图,其中修复位于中心,并在精确坐标处放置一个图钉。

我有界面设置,地图正常工作,只需要启用按钮搜索用户输入的修复,返回lat long,然后将它们转发到地图。我一直在这里寻找几个小时的答案,并尝试了我发现的没有运气的版本..

这是plist:

enter image description here

你可以看到很多修复方法......最好的方法是什么?我不知道怎么从这里开始。

这就是我用来定位地图的原因

func zoomToRegion() {
  let location = CLLocationCoordinate2D(latitude: 62, longitude: 16)
  let region = MKCoordinateRegionMakeWithDistance(location, 700000.0, 900000.0)

  mapView.setRegion(region, animated: true)
}

正如你现在所看到的那样,我只需手动输入一个lat和long,但无论如何都可以。

我最接近它的工作是遵循本指南:http://rshankar.com/how-to-add-mapview-annotation-and-draw-polyline-in-swift/但是我不希望修复程序出现在地图上,直到有人搜索它们,而我无法将该代码转换为我想要的......

感谢您对此有任何帮助或见解!

1 个答案:

答案 0 :(得分:0)

我宁愿把它们存放在lat&只要Double,但无论如何,你应该首先从.plist创建一个NSArray (Read from .plist) 然后过滤该阵列,无论它是否存储相同的lat&用户输入的长值。

guard let filePath = NSBundle.mainBundle().pathForResource("YOUR_FILE_NAME", ofType: "plist"),    
let locationsArray = NSArray(contentsOfFile:filePath) else {
    print("Couldn't load .plist as an array")
    return
}

// TODO: Replace them with the actual user input
let userInputText: String = "ALABA"

// It may not contain any items
let filteredLocations = locationsArray.filter { (element) -> Bool in
    guard let title = element["title"] as? String where
      userInputText == title else { return false }
    return true
}

// To convert String lat & long to Double
let numberFormatter = NSNumberFormatter()
numberFormatter.decimalSeparator = ","

// If you only need the first result:
guard let locationDict = filteredLocations.first as? [String:AnyObject],
    let latString = location["lat"] as? String, 
    let longString = location["long"] as? String,
    let latitude = numberFormatter.numberFromString(latString)?.doubleValue,
    let longitude = numberFormatter.numberFromString(longString)?.doubleValue else {
       print("No result"); return
    }

// Your location
let location = CLLocationCoordinate2D(
    latitude: latitude, 
    longitude: longitude
)

// Do something with your location
let region = MKCoordinateRegionMakeWithDistance(location, 700000.0, 900000.0)
mapView.setRegion(region, animated: true)

但是如果你使用.plist中给出的属性实现一个像LocationData这样的类会更好,并且你会创建一个[LocationData]数组,这样你就可以达到lat&长期的对象属性,而不是字典中的键。

相关问题