UIWebViewなどでローカルのファイルを開きたいときには、NSURLでアクセスできるような形式で保存する必要があります。
下記は、NSData型のデータを保存して、データのNSURLを返すコードです。
// ファイルをキャッシュする際のキー
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let cacheKey = "/test/1"
let fileName = "test.txt"
// ディレクトリのパス
let folderPath=documentsPath+cacheKey
// ファイルのパス
let filePath = documentsPath+cacheKey+"/"+fileName
//ディレクトリとファイルの有無を調べる
let fileManager = NSFileManager.defaultManager()
var isDir : ObjCBool = false
let isFile = fileManager.fileExistsAtPath(filePath, isDirectory: &isDir)
fileManager.fileExistsAtPath(folderPath, isDirectory: &isDir)
//ファイルのパスからNSURLを作成することが出来ます
let url = NSURL(fileURLWithPath: filePath)
//ディレクトリが存在しない場合に、ディレクトリを作成する
if !isDir {
fileManager.createDirectoryAtPath(folderPath ,withIntermediateDirectories: true, attributes: nil, error: nil)
}
//ファイルが存在しない場合に、ファイルを保存する
if isFile {
return url
}else{
//responseは保存しておきたいデータ(NSData型)
response.writeToFile(filePath, atomically: true)
return url
}
DocumentDirectory以外の場所では、writeToFileで保存出来ないので、注意を払う必要があります。


