I am new to Swift 3 and wanted to create a little To-Do-List. But in viewDidLoad the App always crashes, because of the UILongPressGestureRecognizer. I searched in the internet, but I found no working solution.
Here's my code and everytime it says "Thread 1: breakpoint 1.1" in the line with UILongPressGestureRecognizer:
class ViewController: UIViewController, UITableViewDelegate {
@IBOutlet weak var newButton: UIButton!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var editButton: UIButton!
var todoList = Todo.load(){
didSet{
Todo.save(todoList)
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.handleLongPress(_:)))
lpgr.minimumPressDuration = 1.2
tableView.addGestureRecognizer(lpgr)
}
func handleLongPress(_ gesture: UILongPressGestureRecognizer){
if gesture.state != .began { return }
let pt = gesture.location(in: tableView)
let path = tableView.indexPathForRow(at: pt)
if let row = (path as NSIndexPath?)?.row,
let cell = tableView.cellForRow(at: path!){
showPopup(sender: cell, mode: "edit", text: todoList[row], row: row)
}
}
Here is the code for the todo.txt file:
struct Todo {
static func save(_ data: [String]){
if let url = docUrl(for: "todo.txt"){
do {
let str = data.joined(separator: "\n")
try str.write(to: url, atomically: true, encoding: .utf8)
} catch {
print(error)
}
}
}
static func load() -> [String] {
if let url = docUrl(for: "todo.txt"){
do{
let str = try String(contentsOf: url,
encoding: .utf8)
return str.characters
.split {$0 == "\n"}
.map { String($0)}
} catch {
print(error)
}
}
return []
}
private static func docUrl(for filename: String) -> URL? {
let urls = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask)
if let docDir = urls.first {
return docDir.appendingPathComponent(filename)
}
return nil
}
}
Here is my Error-Report:
Error Domain=NSCocoaErrorDomain Code=260 "The file “todo.txt” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users/mkartds/Library/Developer/CoreSimulator/Devices/5D70E1CB-6D29-49E4-BCD1-316B5022F085/data/Containers/Data/Application/34869E75-E498-4674-B504-E7867935E3FE/Documents/todo.txt, NSUnderlyingError=0x61000004a830 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
(lldb)
What should I do?
Assuming you've added
todo.txt
file in your project's target.Try updating
docUrl
method with following,Deactivate your breakpoints: