2016-11-03 4 views
0

スウィフト3で取得フルパスまたは例えば、

let directoryEnumerator = FileManager().enumerator(at: ... 

を使用している場合、私はフォルダから全てのファイルを取得をフルパスに変換

"file:///Volumes/MacOS/fasttemp/Fotos/" 

結果には、先頭のパス(ここでは「/ Volumes/MacOS」)が含まれていません。だから私は得る

"file:///fasttemp/Fotos/2005/" 

フルパスを(列挙子から直接)得るか、それらを変換するにはどうすればよいですか?私はURL関数を使用したいが、文字列関数は仮定で操作しない。あなたがNSURL documentationから、URL可能な限りを使用したい

+0

"/ボリューム/ MacOSのは、" "/" へのシンボリックリンクなので、両方とも "/ fasttemp /写真集/ 2005 /" と「/ボリューム/ MacOSの:古いシステムでは、あなたは realpath()システムコールを使用することができます/ fasttemp/Fotos/"は同じファイルへの絶対パスです。 –

+0

ファイルの特定の表現を取得する関数はありますか?私はそれらを比較するのが好きです。それらをキーとして使用します。彼らが文字列として異なる表現を使用する場合、それは失敗します。 – Peter71

答えて

2

「MacOSのは、」あなたの現在の起動ディスクの名前である場合は、「/ボリューム/ MacOSのは、」シンボリックリンクです"/ fasttemp/Fotos/2005 /"と "/ Volumes/MacOS/fasttemp/Fotos /"は同じファイルへの絶対パスです。

一意のファイル名の表現を取得するには、 にその正規パスのURLを問い合わせることができます。例:

let url = URL(fileURLWithPath: "/Volumes/MacOS/Applications/Utilities/") 
if let cp = (try? url.resourceValues(forKeys: [.canonicalPathKey]))?.canonicalPath { 
    print(cp) 
} 
// Output: "/Applications/Utilities" 

これには、macOS 10.12/iOS 10以降が必要です。

if let rp = url.withUnsafeFileSystemRepresentation ({ realpath($0, nil) }) { 
    let fullUrl = URL(fileURLWithFileSystemRepresentation: rp, isDirectory: true, relativeTo: nil) 
    free(rp) 
    print(fullUrl.path) 
} 
// Output: "/Applications/Utilities" 
+0

優れています。それは「canonicalPath」です。どうもありがとう! – Peter71

+0

Ups、ちょうど情報を得ました、この機能はOSX 10.12でのみ利用可能です! > = 10.9に類似したものはありますか? – Peter71

+0

@ Peter71:更新を参照してください。 –

0

注:

URLオブジェクトは、ローカルファイルを参照するための好ましい方法です。ほとんどの ファイルからデータを読み書きするオブジェクトは、 がファイル参照としてパス名の代わりにNSURLオブジェクトを受け入れるメソッドを持っています。

ここディレクトリからすべてのオブジェクトを取得する方法の例です:

import Foundation 

let manager = FileManager.default 

// Get URL for the current user’s Documents directory 
// Use URL instead of path, it’s more flexible and preferred 
if let documents = manager.urls(for: .documentDirectory, in: .userDomainMask).first, 

    // Get an Enumerator for the paths of all the objects in the directory 
    // but do not descend into directories or packages 
    let directoryEnumerator = manager.enumerator(at: documents, includingPropertiesForKeys: [URLResourceKey.pathKey], options: [.skipsSubdirectoryDescendants, .skipsPackageDescendants]) { 

    // iterate through the objects (files, directories, etc.) in the directory 
    for path in directoryEnumerator { 
    print(path) 
    } 
} 
+0

これはまさに私が思いついたこと(そして私がやったこと)です。私は長い(明示的に)から短いバージョン( "/"のみ)を文字列ベースで自分自身で書くことなく、変換関数を探しています。 – Peter71