将文件保存在swift 3的文件目录下?
我用这个代码将文件保存在swift 3文档目录中:
fileManager = FileManager.default // let documentDirectory = fileManager?.urls(for: .documentDirectory, in: .userDomainMask).first as String var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String path = path + name let image = #imageLiteral(resourceName: "Notifications") let imageData = UIImageJPEGRepresentation(image, 0.5) let bool = fileManager?.createFile(atPath: path, contents: imageData, attributes: nil) print("bool is \(bool)") return true
但正如你所看到的,我没有使用filemanager
来获取文档目录path,因为filemanager
只给出URL而不是string。
问题:
- 如何从文件pipe理器获取string?
- 有没有在我的代码崩溃的机会?
请相反思考。
URL
是处理文件path的推荐方式,因为它包含所有便捷方法来添加和删除path组件和扩展 – 而不是Apple从中移除这些方法的String
。
你不鼓励连接path = path + name
这样的path = path + name
。 这很容易出错,因为你负责所有的斜线path分隔符。
此外,您不需要使用FileManager
创build文件。 Data
有一种将数据写入磁盘的方法。
let fileManager = FileManager.default do { let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false) let fileURL = documentDirectory.appendingPathComponent(name) let image = #imageLiteral(resourceName: "Notifications") if let imageData = UIImageJPEGRepresentation(image, 0.5) { try imageData.write(to: fileURL) return true } } catch { print(error) } return false
func copyandpast(){
var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true); let dbpath :NSString = path[0] as NSString; let strdbpath = dbpath.strings(byAppendingPaths: ["mydb.db"])[0] ; print(strdbpath); let fmnager = FileManager.default; if !fmnager.fileExists(atPath: strdbpath) { let local = Bundle.main.path(forResource: "mydb", ofType: "db"); do { try fmnager.copyItem(atPath: local!, toPath: strdbpath) }catch{ } } }