iOS swift3.0 以把字符串添加到文件结尾的方式保存数据

版权声明:本文为博主原创文章,转载请说明出处:http://blog.csdn.net/amberoot https://blog.csdn.net/amberoot/article/details/79957400

//把字符串写进文件,文件保存在沙盒中Documents路径中

func writeStrToFile(receivedString: NSString) {        

    let str = receivedString as String

    let wr = NSMutableData()

   wr.append(str.data(using:String.Encoding(rawValue: String.Encoding.utf8.rawValue))!)

 

    let manager = FileManager.default

    let urlsForDocDirectory = manager.urls(for:.documentDirectory, in:.userDomainMask)

    let docPath = urlsForDocDirectory[0]

    let file = docPath.appendingPathComponent("Demo.txt")//若不存在该文件,则自动创建

    let writeHandler = try? FileHandle(forWritingTo:file)

    if writeHandler != nil {

         writeHandler!.seekToEndOfFile()

         writeHandler?.write(wr as Data)

    }

        

        

}

 

阅读更多

没有更多推荐了,返回首页