我在应用程序中有一个弹出文本框警报,用户可以在其中输入字符以创建.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"在打印检查?
这是在我的打印检查语句中打印到控制台的内容, []:已保存骑行的名称
答案 0 :(得分:0)
你的" saveRide()"正在立即调用函数。将它放在块中,以便在saveAction上调用它。