Pebble Coding

ソフトウェアエンジニアによるIT技術、数学の備忘録

ios10.3 ファイルパス問題

環境 ios10.3.1
Xcode 8.3.2

        guard let path:String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first else {
            return
        }
        let filename0 = path + "/" + "a.txt"
        if let fp0 = fopen(filename0, "wb") {
            print("fp0 \(fp0)")
        } else {
            print("fp0 is nil")
        }
        
        let filename1 = path + "/" + "ぱ.txt"
        if let fp1 = fopen(filename1, "wb") {
            print("fp1 \(fp1)")
        } else {
            print("fp1 is nil")
        }
        
        let fm = FileManager.default
        try? fm.createDirectory(atPath: path + "/ぱ", withIntermediateDirectories: true, attributes: nil)
        
        let filename2 = path + "/ぱ/" + "ぴ.txt"
        if let fp2 = fopen(filename2, "wb") {
            print("fp2 \(fp2)")
        } else {
            print("fp2 is nil")
        }
        
        let filename3 = path + "/ぱ/" + "b.txt"
        if let fp3 = fopen(filename3, "wb") {
            print("fp3 \(fp3)")
        } else {
            print("fp3 is nil")
        }
        
        let filename4 = (filename3 as NSString).fileSystemRepresentation
        if let fp4 = fopen(filename4, "wb") {
            print("fp4 \(fp4)")
        } else {
            print("fp4 is nil")
        }
[結果]
fp0 0x0000000100d01c78
fp1 0x0000000100d11808
fp2 is nil
fp3 is nil
fp4 0x0000000100c16da8

fopenでのファイル作成では、濁点、半濁点名を付けたフォルダ名をパスに含むとfopenに失敗するようです。
fopenに渡す場合はNSStringのfileSystemRepresentationで変換すればよいようです。

参考:

https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/APFS_Guide/FAQ/FAQ.html#//apple_ref/doc/uid/TP40016999-CH6-DontLinkElementID_3:Apple APFS Guide

iOS10.3のファイルパス問題について