2015-11-23 15 views

Antwort

16

Sie können Ihre URL in zwei Teil trennen. Welches ist unter

let str : NSString = "www.music.com/Passion/PassionAwakening.mp3" 
    let path : NSString = str.stringByDeletingLastPathComponent 
    let ext : NSString = str.lastPathComponent 

    print(path) 
    print(ext) 

Ausgabe

www.music.com/Passion 
PassionAwakening.mp3 

Für weitere Informationen gegeben bitte einen Blick

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/ManipulatingPaths.html

+1

Beachten Sie, dass diese Methode nur mit Dateipfaden arbeitet (nicht zum Beispiel Stringdarstellungen von URLs). – user3441734

+0

Was meinst du mit String-Darstellung? –

+0

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/#//apple_ref/occ/instp/NSString/stringByDeletingLastPathComponent – user3441734

4
let str = "11/Passion/01PassionAwakening.mp3" 
if !str.isEmpty { 
    let components = str.characters.split("/") 
    let head = components.dropLast(1).map(String.init).joinWithSeparator("/") 
    let tail = components.dropFirst(components.count-1).map(String.init)[0] 

    print("head:",head,"tail:", tail) // head: 11/Passion tail: 01PassionAwakening.mp3 
} else { 
    print("path should not be an empty string!") 
} 
+0

Swift 3.0.1 benötigt Syntax: Split (Trennzeichen: "/") – clearlight

4

Swift 3.0 Version

if !str.isEmpty { 
     let components = str.characters.split(separator: "/") 
     let head = components.dropLast(1).map(String.init).joined(separator: "/") 
     let words = components.count-1 
     let tail = components.dropFirst(words).map(String.init)[0] 

     print("head:",head,"tail:", tail) // head: 11/Passion tail: 01PassionAwakening.mp3 
    } else { 
     print("path should not be an empty string!") 
    } 
5

diese 3.0 als auch für Swift arbeitet:

let fileName = NSString(string: "11/Passion/01PassionAwakening.mp3").lastPathComponent 
4

Sie sollte mit Legacy-NS Objective-C-Klassen und manuellem Weg String Splitting wo möglich wirklich abschaffen. Verwenden Sie URL statt:

let url = URL(fileURLWithPath: "a/b/c.dat") 
let path = url.deletingLastPathComponent().relativePath // 'a/b' 
let file = url.lastPathComponent // 'c.dat' 
Verwandte Themen