2017-02-10 16 views
0

Swift 3を使用してiOSで一時ディレクトリを作成する際に問題があります。FileManager.temporaryDirectoryから一時ディレクトリのURLを取得しましたが、FileManager.createDirectoryを使用してディレクトリを作成しようとしていますが、存在しているように見え、ファイルを作成できません。私は間違って何をしていますか?一時ディレクトリを作成できません

let fileManager = FileManager.default 
let tempDir = fileManager.temporaryDirectory 
let tempDirString = String(describing: tempDir) 
print("tempDir: \(tempDir)") 
print("tempDirString: \(tempDirString)") 
if fileManager.fileExists(atPath: tempDirString) { 
    print("tempDir exists") 
} else { 
    print("tempDir DOES NOT exist") 
    do { 
     try fileManager.createDirectory(at: tempDir, withIntermediateDirectories: true, attributes: nil) 
     print("tempDir created") 
     if fileManager.fileExists(atPath: tempDirString) { 
      print("tempDir exists") 
     } else { 
      print("tempDir STILL DOES NOT exist") 
     } 
    } catch { 
     print("tempDir NOT created") 
    } 
} 

これは出力を生成します。あなたはfileManager.fileExists(atPath: tempDirString)に渡している

tempDir: file:///private/var/mobile/Containers/Data/Application/D28B9C5E-8289-4C1F-89D7-7E9EE162AC27/tmp/ 
tempDirString: file:///private/var/mobile/Containers/Data/Application/ D28B9C5E-8289-4C1F-89D7-7E9EE162AC27/tmp/ 
tempDir DOES NOT exist 
tempDir created 
tempDir STILL DOES NOT exist 
+0

ディレクトリを作成する必要はありません。すでに作成されています。 –

+0

http://stackoverflow.com/questions/16176911/nsurl-path-vs-absolutestringもご覧ください。 –

答えて

3

tempDirString文字列は、文字列が含まれていますが、文字列は、ファイルパスではありません。人間が読める目的のための記述であり、機械で読める目的のためのものではありません。実際には、有効なURL文字列でもありません(スペースを確認してください!)。

あなたがパスをしたい場合は、この行を置き換える:

let tempDirString = String(describing: tempDir) 

を、代わりに文字列としてパスを取得するためにtempDirStringにNSURLのpath関数の結果を割り当てる:

let tempDirString = tempDir.path 

参照してください。 https://developer.apple.com/reference/foundation/nsurl/1408809-path

関連する問題