Converting URL to String and back again

后端 未结 10 1298
攒了一身酷
攒了一身酷 2020-12-22 20:29

So I have converted an NSURL to a String. So if I println it looks like file:///Users/... etc.

Later I want this

相关标签:
10条回答
  • 2020-12-22 21:09

    2020 | SWIFT 5.1:

    From STRING to URL:

    let url = URL(fileURLWithPath: "//Users/Me/Desktop/Doc.txt")
    

    From URL to STRING:

    let a = String(describing: url)       // "file:////Users/Me/Desktop/Doc.txt"
    let b = "\(url)"                      // "file:////Users/Me/Desktop/Doc.txt"
    let c = url.absoluteString            // "file:////Users/Me/Desktop/Doc.txt"
    let d = url.path                      // "/Users/Me/Desktop/Doc.txt" 
    

    BUT value of d will be invisible due to debug process, so...

    THE BEST SOLUTION:

    let e = "\(url.path)"                 // "/Users/Me/Desktop/Doc.txt"
    
    0 讨论(0)
  • 2020-12-22 21:11

    Swift 3 used with UIWebViewDelegate shouldStartLoadWith

      func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
        let urlPath: String = (request.url?.absoluteString)!
        print(urlPath)
        if urlPath.characters.last == "#" {
            return false
        }else{
            return true
        }
    
    }
    
    0 讨论(0)
  • 2020-12-22 21:13
    let url = URL(string: "URLSTRING HERE")
    let anyvar =  String(describing: url)
    
    0 讨论(0)
  • 2020-12-22 21:16

    Swift 3 version code:

    let urlString = "file:///Users/Documents/Book/Note.txt"
    let pathURL = URL(string: urlString)!
    print("the url = " + pathURL.path)
    
    0 讨论(0)
  • 2020-12-22 21:19

    NOTICE: pay attention to the url, it's optional and it can be nil. You can wrap your url in the quote to convert it to a string. You can test it in the playground.
    Update for Swift 5, Xcode 11:

    import Foundation
    
    let urlString = "http://ifconfig.me"
    // string to url
    let url = URL(string: urlString)
    //url to string
    let string = "\(url)"
    // if you want the path without `file` schema
    // let string = "\(url.path)"
    
    0 讨论(0)
  • 2020-12-22 21:20

    There is a nicer way of getting the string version of the path from the NSURL in Swift:

    let path:String = url.path
    
    0 讨论(0)
提交回复
热议问题