ios - Append some text at the end of text file in swift -
this question has answer here:
- append text or data text file in swift 3 answers
i using following code getting errors.
"can not convert value of type nsurl int32"
at line:
if let filehandle = nsfilehandle(filedescriptor: fileurl, closeondealloc: &err).
and getting error
"type of expression ambiguous without more context" @ line
if !data.writetourl(fileurl, options: .datawritingatomic, error: &err)
code:
let dir:nsurl = nsfilemanager.defaultmanager().urlsfordirectory(nssearchpathdirectory.cachesdirectory, indomains: nssearchpathdomainmask.userdomainmask).last nsurl let fileurl = dir.urlbyappendingpathcomponent("log.txt") let string = "\(nsdate())\n" let data = string.datausingencoding(nsutf8stringencoding, allowlossyconversion: false)! if nsfilemanager.defaultmanager().fileexistsatpath(fileurl.path!) { var err:nserror? if let filehandle = nsfilehandle(filedescriptor: fileurl, closeondealloc: &err) { filehandle.seektoendoffile() filehandle.writedata(data) filehandle.closefile() } else { print("can't open filehandle \(err)") } } else { var err:nserror? if !data.writetourl(fileurl, options: .datawritingatomic, error: &err) { print("can't write \(err)") } }
your code looks swift 1 me , then, it's not valid swift 1 either. if using swift 2 or later, try this:
let dir = nsfilemanager.defaultmanager().urlsfordirectory(nssearchpathdirectory.cachesdirectory, indomains: nssearchpathdomainmask.userdomainmask).last! let fileurl = dir.urlbyappendingpathcomponent("log.txt") let string = "\(nsdate())\n" let data = string.datausingencoding(nsutf8stringencoding, allowlossyconversion: false)! if nsfilemanager.defaultmanager().fileexistsatpath(fileurl.path!) { { let filehandle = try nsfilehandle(forwritingtourl: fileurl) filehandle.seektoendoffile() filehandle.writedata(data) filehandle.closefile() } catch { print("can't open filehandle \(error)") } } else { { try data.writetourl(fileurl, options: .datawritingatomic) } catch { print("can't write \(error)") } }
Comments
Post a Comment