我在应用程序中有一个弹出文本框警报,用户可以在其中输入字符来为 .txt 文件创建自定义名称,然后保存该文件。该文件名存储在名为rideContent 的全局变量中。当我调用 saveRide() 函数时,一个充满字符串信息的文件存储在 .txt 中,应该使用用户在文本框中创建的文件名,但是存储在其中的文件名数组为空。
我是否在 stopAction 函数中乱序或太早调用了 save 函数,这就是数组为空的原因?或者我是否以错误的方式调用rideName =rideContent?即rideName =rideContent[-1]?
我希望用户输入自定义名称,并将其用作保存和加载文件的标识符。任何帮助将不胜感激!
这里我调用一个名为rideContent的全局变量:
var rideContent = [String]()
这里我调用保存函数:
@IBAction func stopAction(sender: UIButton) {
let alert = UIAlertController(title: "Ride Stopped", message: "Give a title to your ride", preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "Save", style: .Default,
handler: { (action:UIAlertAction) -> Void in
// Allow for text to be added and appended into the RideTableViewController
let textField = alert.textFields!.first
rideContent.append(textField!.text!)
// Update permanent storage after deleting a ride
NSUserDefaults.standardUserDefaults().setObject(rideContent, forKey: "rideContent")
// Segue to the Ride details page
self.performSegueWithIdentifier("ShowRideDetail", sender: nil)
})
let cancelAction = UIAlertAction(title: "Cancel",
style: .Default) { (action: UIAlertAction) -> Void in
}
alert.addTextFieldWithConfigurationHandler {
(textField: UITextField) -> Void in
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
//Show the alert
presentViewController(alert, animated: true, completion: nil)
// Stop the timer
timer.invalidate()
// Stop location updates
self.stopLocation()
// Save the ride
saveRide()
}
以下是保存到文本文件的代码:
func saveRide() {
let rideName = rideContent
// Print Check
print("\(rideName) : the name of the saved ride")
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
let fileName = ("\(documentsDirectory)")+("\(rideName)")+(".txt")
print("\(fileName)This is firt check")
var content: String
// Adding elasped time information to the bicycle ride
// Content Order: Seconds, Minutes, Hours, Distance \n coordinates
content = ("\(seconds) Seconds, ")+("\(minutes) Minutes, ")+("\(hours) Hours, ") + ("\(self.distanceLabel.text!)") + "\n"
// Create a for loop to add each recorded coordinate value to the content list to later be added and displayed as a polyline
for coord in self.coords {
content = content + ("\(coord.latitude) " + "," + "\(coord.longitude) " + "\n")
}
do{
try content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding)
}catch _ {
}
}
Here是用户可以输入自定义名称的屏幕截图。根据用户输入的乘车名称,打印检查中的乘车名称不应该称为“Morning Ride”吗?
这是我的打印检查语句中打印到控制台的内容,[]:已保存行程的名称
最佳答案
您的“saveRide()”函数正在立即被调用。将其放入 block 内,以便在您的 saveAction 上调用它。
关于ios - 如何保存和加载具有自定义名称的 .txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35586133/