I was trying to encode a URL. The code works fine when I encode files in my bundle. But when I tried to encode the files written to Documents and Cache, the program fails to encode.
Here is my encoder:
private class func EncodeURL(_ url:URL,encoding:UInt) ->String {
do{
return try NSString(contentsOf: url, encoding: encoding) as String
}catch{}
return ""
}
I'm using the following three:
content = EncodeURL(url, encoding: String.Encoding.utf8.rawValue)
content = EncodeURL(url, encoding: 0x80000632)
content = EncodeURL(url, encoding: 0x80000631)
And none of them work.
Here is the code I use to generate files. I'm putting them in the Documents Folder.
func writeFile(fileName:String,data:NSData)->Bool{
guard let filePath = createFilePath(fileName: fileName) else{
return false
}
return data.write(toFile:filePath,atomically:true)
}
func createFilePath(fileName:String)->String?{
let dir = getCachePath()
if(!dirExists(dir: dir) && !createDir(dir: dir)){
return nil
}
let filePath = dir + fileName
if(fileExists(path: filePath)){
do{
try getFileManager().removeItem(atPath: filePath)
}catch{
return nil
}
}
return filePath
}
func getCachePath()->String{
var cacheDir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, .userDomainMask, true).first!
if(!cacheDir.hasSuffix("/")){
cacheDir += "/"
}
cacheDir += CACHEPATH + "/" //CACHEPATH is just NSHomeDirectory()
return cacheDir
}
writeFile(fileName: String(timeInterval)+"_"+somestring+".txt", data: data! as NSData)
Above is how I generate the files.
And how I passed URL is:
url = URL(string:getCachePath()+bookname+".txt")
passing this to
EncodeURL(url:URL,encoding:UInt)
My URL is:
/Users/houki/Library/Developer/CoreSimulator/Devices/67C921C8-18A3-4A3F-81FF-C3AF04E88049/data/Containers/Data/Application/85633861-90E6-4DB8-95B0-86C359C74C6B/Documents//Users/houki/Library/Developer/CoreSimulator/Devices/67C921C8-18A3-4A3F-81FF-C3AF04E88049/data/Containers/Data/Application/85633861-90E6-4DB8-95B0-86C359C74C6B/1511757881.83107_bigbrother.txt
Does this look weird? I'm testing it on a simulator though.
But actually this worked just fine when I tried to read files through the path. The following code is working.
let contentsofPath = try FileManager.default.contentsOfDirectory(atPath: getCachePath())
