简体   繁体   中英

How to use FileManager correctly?

I use

let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group....")?.appendingPathComponent("hello")
            let data = Data("289".utf8)
            try! data.write(to: url!)
            
            let url2 = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.co...")?.appendingPathComponent("mannschaft")
            let data2 = Data("114".utf8)
            try! data2.write(to: url2!)

to write some data on a file.

And later i use these two on different swift files :

let teamId: String = {
            let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.co....")?.appendingPathComponent("hello")
            let data = try! Data(contentsOf: url!)
            let string = String(data: data, encoding: .utf8)!
            return string
            }()

and

let vergleichmannschaft: String = {
        let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.co...")?.appendingPathComponent("mannschaft")
        let data = try! Data(contentsOf: url!)
        let string = String(data: data, encoding: .utf8)!
        return string
        }()

to read it. But the simulator chrashes and says: Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=260 "The file “mannschaft” couldn't be opened because there is no such file." UserIn Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=260 "The file “mannschaft” couldn't be opened because there is no such file." UserIn

"hello" works but not "mannschaft"

You should never use try! unless you are sure that this will never fail. You need to make sure that the file exists on that location or return an emptyString. You should also make it a computed property. Make sure you have already created your file before fetching its contents. Btw you should add the ".txt" pathExtension to your text file names:

var vergleichmannschaft: String {
    guard let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.co...")?.appendingPathComponent("mannschaft.txt") else {
        return ""
    }
    return (try? String(contentsOf: url,encoding: .utf8)) ?? ""        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM