将 URL 转换为字符串并再次返回 [英] Converting URL to String and back again

查看:32
本文介绍了将 URL 转换为字符串并再次返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我将 NSURL 转换为 String.所以如果我 println 它看起来像 file:///Users/... 等等.

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

稍后我希望将其作为 NSURL 返回,因此我尝试将其转换回如下所示,但我丢失了上面字符串版本中出现的两个正斜杠,这反过来又破坏了代码作为 url 无效.

Later I want this back as an NSURL so I try and convert it back as seen below, but I lose two of the forward slashes that appear in the string version above, that in turn breaks the code as the url is invalid.

为什么我的转换回 NSURL 删除了我给它的 String 中的两个正斜杠,以及如何转换回 NSURL> 包含三个正斜杠?

Why is my conversion back to NSURL removing two forward slashes from the String I give it, and how can I convert back to the NSURL containing three forward slashes?

var urlstring: String = recordingsDictionaryArray[selectedRow]["path"] as String
println("the url string = \(urlstring)")
// looks like file:///Users/........etc
var url = NSURL.fileURLWithPath(urlstring)
println("the url = \(url!)")
// looks like file:/Users/......etc

推荐答案

fileURLWithPath() 用于将普通文件路径(例如/path/to/file")转换为 URL.您的 urlString 是包含方案的完整 URL 字符串,因此您应该使用

fileURLWithPath() is used to convert a plain file path (e.g. "/path/to/file") to an URL. Your urlString is a full URL string including the scheme, so you should use

let url = NSURL(string: urlstring)

将其转换回NSURL.示例:

let urlstring = "file:///Users/Me/Desktop/Doc.txt"
let url = NSURL(string: urlstring)
println("the url = \(url!)")
// the url = file:///Users/Me/Desktop/Doc.txt

这篇关于将 URL 转换为字符串并再次返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆