Search code examples
iosnsurlnsfilemanager

filemanager.createFileAtPath works not correctly


I try to create a PLIST-File with the NSFileManager and the method createFileAtPath. In the end, the file was created, it has the size of 0 Bytes, and i even can see the specific PLIST-Icon for that file in the Finder. But when i want to open it (for example with Xcode) it says:The data couldn't be read because it isn't in the correct format. I want to write to this file but when its not in the correct format i can't do this.

There is something wrong with the File-creation but i don't know what it is. I hope you can help me with this. Here is my code:

pListPath = NSURL(fileURLWithPath: reportsPath.path!).URLByAppendingPathComponent("myReports.plist", isDirectory: false)

                let data: NSData = NSData()
                var isDir: ObjCBool = false

                if fileManager.fileExistsAtPath(pListPath.path!, isDirectory: &isDir)
                    {
                        print("File already exits")
                    }
                    else
                    {
                        let success = fileManager.createFileAtPath(pListPath.path!, contents: data, attributes: nil)

                        print("Was file created?: \(success)")
                        print("plistPath: \(pListPath)")
                    }

reports.path = .../UserDir/.../Documents/Reports

Any help is highly appreciated.


Solution

  • filemanager.createFileAtPath works absolutely correctly,
    but you're creating an empty file by writing an empty NSData object to disk.
    NSData objects are not implicitly serialized to a property list.

    Either use the NSPropertyListSerialization class or – simpler - write an empty dictionary to disk.

    let dictionary = NSDictionary()
    let success = dictionary.writeToURL(pListPath, atomically: true)
    print("Was file created?: \(success)")
    print("plistPath: \(pListPath)")
    

    PS: you don't need to create an URL from an URL

    pListPath = reportsPath.URLByAppendingPathComponent("myReports.plist", isDirectory: false)
    

    but I recommend to use more descriptive variable names to distinguish String paths and NSURL e.g. pListURL and reportsURL