'的NSURLRequest&#39?;没有名为' URL'的成员 - 斯威夫特

时间:2015-02-13 12:55:10

标签: url swift webview uiwebview

嗨,我真的很喜欢在Swift中编码,我正在尝试遵循本书中的代码:http://www.apress.com/9781484202098。学习James Bucanek的iOS 8 App Development第2版

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

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

表示' NSURLRequest?'没有名为' URL'的成员。

我试过谷歌搜索答案,但遗憾的是没有遇到任何问题。我能找到的任何回复似乎都表明我的代码应该有效(例如How to get url which I hit on UIWebView?)。这似乎是最接近的答案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。有没有人建议如何删除这个?

1 个答案:

答案 0 :(得分:1)

requestUIWebView上的可选属性:

var request: NSURLRequest? { get }

stringByAddingPercentEscapesUsingEncoding还会返回一个可选的:

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