'NSURLRequest?' 没有名为 'URL' - Swift 的成员

'NSURLRequest?' does not have a member named 'URL' - Swift

您好,我是 Swift 中编码的新手,我正在尝试遵循本书中的代码:http://www.apress.com/9781484202098。学习 iOS 8 App Development 2nd Edition by James Bucanek

特别是,我正在完成第 3 章 - 构建一个 URL 缩短应用程序,但尽管我已经准确复制了代码,但我在第 76 页的代码中遇到错误:

if let toShorten = webView.request.URL.absoluteString {

其中指出 'NSURLRequest?' 没有名为 'URL' 的成员。

我试过用谷歌搜索一个答案,但很遗憾没有找到任何答案。我能找到的任何回复似乎都表明我的代码应该可以工作(例如 How to get url which I hit on UIWebView?). This seems to have the closest answer SWIFT: Why I can't get the current URL loaded in UIWebView? 但解决方案似乎对我不起作用。如果我在请求后添加 ? ,它至少会构建它,但我随后返回了一个 nil 变量。

我正在使用 Xcode v6.1.1。这是 ViewController.swift:

中出现错误的一段代码
    let GoDaddyAccountKey = "0123456789abcdef0123456789abcdef" //this is replaced by my actual account key in my own code
    var shortenURLConnection: NSURLConnection?
    var shortURLData: NSMutableData?

    @IBAction func shortenURL( AnyObject ) {

        if let toShorten = webView.request?.URL.absoluteString { // ? now added

        let encodedURL = toShorten.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
        let urlString = "http://api.x.co/Squeeze.svc/text/\(GoDaddyAccountKey)?url=\(encodedURL)"
        shortURLData = NSMutableData()
        if let firstrequest = NSURL(string: urlString) //added if here and removed !
        let request = NSURLRequest(URL:firstrequest)
        shortenURLConnection = NSURLConnection(request:request, delegate:self)
        shortenButton.enabled = false
        }
        }
    }

如果您对我如何解决这个问题有任何建议,我将不胜感激!

更新:

根据下面 Ashley 的建议,我修改了我的代码,使其不再出现错误(参见上面的评论)。不过,现在已经不是运行了。这似乎是因为 urlString 被创建为 http://api.x.co/Squeeze.svc/text/d558979bb9b84eddb76d8c8dd9740ce3?url=Optional("http://www.apple.com/")。因此,问题在于包含的 Optional(),从而使其成为无效的 URL。请问有人对如何删除它有什么建议吗?

requestUIWebView 上的可选 属性:

var request: NSURLRequest? { get }

还有stringByAddingPercentEscapesUsingEncoding returns一个可选的:

func stringByAddingPercentEscapesUsingEncoding(_ encoding: UInt) -> String?

您需要在几个地方使 可选绑定 成为用户:

if let toShorten = webView.request?.URL.absoluteString {

    if let encodedURL = toShorten.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {

        let urlString = "http://api.x.co/Squeeze.svc/text/\(GoDaddyAccountKey)?url=\(encodedURL)"
        shortURLData = NSMutableData()

        if let firstrequest = NSURL(string: urlString) {  // If a method can return a nil, don't force unwrap it
            let request = NSURLRequest(URL:first request)
            shortenURLConnection = NSURLConnection(request:request, delegate:self)
            shortenButton.enabled = false
        }

    }
}

详情见Apple's docs on optional chaining

Apple's docs for NSURL class