小编Rom*_*ain的帖子

在Swift中使用NSURL读取文本文件

我想阅读并显示位于URL的文本文件的内容.我正在为优胜美地编写Mac应用程序,我需要使用Swift,但我坚持这一点.

这是我的代码:

let messageURL = NSURL(string: "http://localhost:8888/text.txt")
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(messageURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in

        var urlContents = NSString(contentsOfURL: location, encoding: NSUTF8StringEncoding, error: nil)

        println((urlContents))


    })
Run Code Online (Sandbox Code Playgroud)

我尝试使用NSString.stringWithContentsOfURL来做,但它似乎在OS X 10.10上已被弃用.

位于服务器上的文本文件只有一行(UTF8).

任何线索?谢谢

macos nsurl swift

8
推荐指数
1
解决办法
4817
查看次数

使用iCloud Documents Storage的最佳方式

我目前在iOS应用程序中使用本地存储.用户数据存储在文档目录中,现在我计划使用iCloud Documents存储.

这是我打算如何做到的:

  1. 检查设备上是否有iCloud可用

  2. 如果是,请使用URLForUbiquityContainerIdentifier获取iCloud容器URL

  3. 将新文件和文档保存到此新URL

为此,我使用此代码将返回文档文件夹的URL(iCloud或本地)

class CloudDataManager {

    class func getDocumentDiretoryURL() -> NSURL {
        let localDocumentsURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: .UserDomainMask).last! as NSURL
        let iCloudDocumentsURL = NSFileManager.defaultManager().URLForUbiquityContainerIdentifier(nil)?.URLByAppendingPathComponent("Documents")

        if userDefault.boolForKey("useCloud") && iCloudDocumentsURL != nil  {
            return iCloudDocumentsURL!
        } else {
            return localDocumentsURL
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是最好的做法吗?如果有一天iCloud不可用,我担心会出现问题,因此将使用本地目录而不是云容器,并且将为空.谢谢.

ios icloud swift

8
推荐指数
2
解决办法
5878
查看次数

标签 统计

swift ×2

icloud ×1

ios ×1

macos ×1

nsurl ×1