如何在Mac上使用Swift讀取和寫入文件?

[英]How can I read from and write to files using Swift on a mac?


I've been looking all over the Internet for an answer to this one, and every answer I've gotten either hasn't worked, is enormously complex, is for iOS only, or a combination of the three. I am just looking for a simple way to perform file I/O in Swift for use on a Mac. So I guess that a way to mix c++ and swift would also work, but for that I've had the same problems as before. Any help would be greatly appreciated!

我一直在互聯網上尋找這個問題的答案,而且我得到的每一個答案都沒有用,非常復雜,僅適用於iOS,或者是三者的組合。我只是在尋找一種在Swift中執行文件I / O以便在Mac上使用的簡單方法。所以我想混合使用c ++和swift的方法也可行,但為此我遇到了和以前一樣的問題。任何幫助將不勝感激!

2 个解决方案

#1


11  

There are many options, it depends what you're trying to write and also the size/etc of the data (hundreds of megabytes of data requires different techniques).

有很多選擇,它取決於您要編寫的內容以及數據的大小/等(數百兆字節的數據需要不同的技術)。

But the simplest method is:

但最簡單的方法是:

import Cocoa

var str = "Hello, playground"

// get URL to the the documents directory in the sandbox
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL

// add a filename
let fileUrl = documentsUrl.URLByAppendingPathComponent("foo.txt")

// write to it
str.writeToURL(fileUrl, atomically: true, encoding: NSUTF8StringEncoding, error: nil)

One thing that might be catching you out is OS X has strict sandboxing to prevent which parts of the disk you can write to. As a security measure for users pasting random code into Xcode and to prevent bugs erasing somebody's entire hard drive... the Playground enforces the sandbox although many mac apps do not use sandboxing (it's usually only enabled for apps deployed in Apple's store).

有一件事可能會讓你感到困惑的是OS X有嚴格的沙盒來防止你可以寫入磁盤的哪些部分。作為一種安全措施,用戶將隨機代碼粘貼到Xcode中並防止錯誤刪除某人的整個硬盤...... Playground強制執行沙盒,盡管許多mac應用程序不使用沙盒(通常只對Apple商店中部署的應用程序啟用)。

Your app has a sandbox on the disk that you can write to, this is what NSFileManager() is returning URL for above.

您的應用程序在磁盤上有一個可以寫入的沙箱,這就是NSFileManager()返回上面的URL。

To punch a hole in the sandbox to the rest of the disk, you need to involve the user. Eg if they drag a file onto your app icon, you can write to it. If they select a file in an open or save panel then you can write to that. If the user selects a directory, or even the root of the file system, you can write to the all descendants of the selection.

要將沙箱中的孔打到磁盤的其余部分,您需要讓用戶參與進來。例如,如果他們將文件拖到您的應用程序圖標上,您可以寫入它。如果他們在打開或保存面板中選擇文件,那么您可以寫入該文件。如果用戶選擇目錄,甚至是文件系統的根目錄,則可以寫入選擇的所有后代。

It's also possible to persist access to a file/directory across app launches, although I've never looked into how that works. NSDocumentController does it for you, if you use that for a document based app.

也可以在應用程序啟動期間持久訪問文件/目錄,盡管我從未研究過它是如何工作的。 NSDocumentController為您完成,如果您將其用於基於文檔的應用程序。

#2


7  

Abhi Beckert's code updated to Swift 3:

Abhi Beckert的代碼更新為Swift 3:

import Cocoa

var str = "Hello, playground"

// get URL to the the documents directory in the sandbox
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as NSURL

// add a filename
let fileUrl = documentsUrl.appendingPathComponent("foo.txt")

// write to it
try! str.write(to: fileUrl!, atomically: true, encoding: String.Encoding.utf8)

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/08/12/1a9bd1d0c452bfe2f876384f4c380186.html



 
  © 2014-2022 ITdaan.com 联系我们: