我在Swift中使用iOS MapKit。我获得路线指示的表格视图。然后,将它们保存到文本文件(Roads.txt)中。进入文本文件后,我想剥离除道路名称以外的所有内容。这意味着我想删除诸如“ North”,“ Turn”,“ Right”等之类的单词。在Swift中有没有办法做到这一点,还是必须将文件保存到数据库并在那里进行更改?
我的代码有效,如下所示:
// Assign variables
let steps = directionsArray[indexPath.section].route.steps
let step = steps[indexPath.row]
let instructions = step.instructions
let distance = step.distance.kilometers()
// Save Directions to text file
let directions = ["\(instructions) - \(distance),"]
let filePath = getDocumentsDirectory().stringByAppendingPathComponent("Roads.txt")
let directionstext = directions.joinWithSeparator("\n")
do {
try directionstext.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
} catch {
print ("Error it did not write to file")
}
//read directions from text file
let file = "Roads.txt" // read from this file
if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)
do {
let Direc = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
print(Direc)
}
catch {print("failed to find file")}
}
好的,根据以上信息,我认为有两种可能的路线可以使用(双关语)...
选项1:配置“后端”或信息源,以便它可以将指令分两部分(方向和街道)传递,这样您就可以丢弃创建所需文件时不需要的部分。这将是简单而整洁的,但可能会或可能不会。
选项2:过滤文件以删除不需要的信息。为了说明该理论,我们假设只有两种可能的指令:“左转到”和“右转到”。然后,您可以使用以下代码从文件中剥离所有指令:
let possibleInstructions = ["Turn left onto ", "Turn right onto "]
for instruction in possibleInstructions {
direc = direc.stringByReplacingOccurrencesOfString(instruction, withString: "")
}
direc
您正在阅读的文件在哪里,是该文件中possibleInstructions
可能出现的所有可能的指令的数组。因此,例如,这将需要:
左转到Infinite Loop-0.00,右转到N De Anza Blvd-0.08,左转到I-280 S-0.12,右转到CA-87-7.81,右转到Guadalupe Parkway S-0.25,左转到CA-87 S-0.85
然后返回:
无限循环-0.00,N德安扎大道-0.08,I-280 S-0.12,CA-87-7.81,瓜达卢佩大路S-0.25,插在CA-87 S-0.85上
显然,可能的指令列表将比这更长,并且您将需要额外的代码来处理特殊情况,例如“将Exit X合并到”,但听起来这可能对以后的过程构成挑战。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句