向文件中写入东西 ios中的程序都是储存在沙盒之中的,向文件中写入文件,就是先提取路径 再创建数据 随后再输入
代码如下
import UIKit class ViewController: UIViewController { override func viewDidLoad() { var url = NSURL() super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //读出文件的相关操作 //声明搜寻的路径 从主路径中寻去 可扩展的去寻找 var sp = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask,true) //如果搜索到的话 if sp.count > 0 { //声明读入的路径 var url = NSURL(fileURLWithPath: "\(sp[0])/data.txt") //输出路径 print(url) var data = NSMutableData() //添加数据 data.appendData("Hello Swift\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) //写入文件 data.writeToFile(url.path!, atomically: true) print("end") } }随后就会输出url的路径 终端用spotlight 搜索 terminal
data.txt不用考虑 随后打开终端,复制文件名 随后会看到data.txt,就会看到hello swift
e:///Users/hznucai/Library/Developer/CoreSimulator/Devices/F3C4A8B5-E455-4603-BD0B-D8D42F15C497/data/Containers/Data/Application/8896B098-8187-4B1C-9FEF-93B371F5E2BF/Dor/CoreSimulator/Devices/F3C4A8B5-E455-4603-BD0B-D8D42F15C497/data/Containers/Data/Application/8896B098-8187-4B1C-9FEF-93B371F5E2BF/Documents/data.txt
file:///Users/hznucai/Library/Developer/CoreSimulator/Devices/F3C4A8B5-E455-4603-BD0B-D8D42F15C497/data/Containers/Data/Application/8896B098-8187-4B1C-9FEF-93B371F5E2BF/Documents/data.txt