SWIFT:为什么"NSURL(string:"返回Nil,即使它在浏览器中是一个有效的URL?

5

前两个示例链接有效,第三个返回NIL。

为什么NSUrl返回nil,即使在浏览器中它是一个有效的URL?

我需要对字符串进行更多处理吗?

这是我的代码:

import UIKit
import Foundation

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSXMLParserDelegate {

var myFeed : NSArray = []
var url : NSURL!
var feedURL : NSURL!
var selectedFeedURL = String()

@IBOutlet var tableFeeds: UITableView!
@IBOutlet var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Set feed url.
    //url = NSURL(string: "http://www.skysports.com/rss/0,20514,11661,00.xml")!  //This seems to work
    //url = NSURL(string: "http://www.formula1.com/rss/news/latest.rss")!  //This seems to work
    url = NSURL(string: "http://www.multirotorusa.com/feed/")!

    loadRss(url);
}

func loadRss(data: NSURL) {
    var myParser : XmlParserManager = XmlParserManager.alloc().initWithURL(data) as XmlParserManager
    myFeed = myParser.feeds

    tableFeeds.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return myFeed.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    var dict : NSDictionary! = myFeed.objectAtIndex(indexPath.row) as NSDictionary

    cell.textLabel?.text = myFeed.objectAtIndex(indexPath.row).objectForKey("title") as? String
    cell.detailTextLabel?.text = myFeed.objectAtIndex(indexPath.row).objectForKey("description") as? String
    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    var indexPath: NSIndexPath = self.tableFeeds.indexPathForSelectedRow()!
    var selectedFeedURL = myFeed.objectAtIndex(indexPath.row).objectForKey("link") as String
    selectedFeedURL =  selectedFeedURL.stringByReplacingOccurrencesOfString(" ", withString:"")
    selectedFeedURL =  selectedFeedURL.stringByReplacingOccurrencesOfString("\n", withString:"")

   // feedURL = NSURL(fileURLWithPath: selectedFeedURL)  //This returns with: URL +   /%09%09 -- file:///
    feedURL = NSURL(string: selectedFeedURL)  //This returns with NIL

    println("Selected Feed URL: \(selectedFeedURL)")
    println("Feed URL: \(feedURL)")

    if feedURL != nil {
        let request : NSURLRequest = NSURLRequest(URL: feedURL!)
        webView.loadRequest(request)
        println("Feed URL: \(feedURL)")  //Doesn't make it here
    }
  }
}

有什么建议吗?

你确定它返回了 nil 吗?对我来说似乎完全正常。 - bjtitus
当URL中存在未转义的字符时,包括末尾空格时,也可能会发生这种情况。 - gone
4个回答

8
你应该像这样对URL进行URL编码:
selectedFeedUrl = selectedFeedUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

使用您的方法,我得到了这个链接:http://www.multirotorusa.com/dji-phantom-dont-be-annoying/%09%09,但是网页无法找到。为什么链接末尾会有 %09%09,我该如何去掉它? - Attila Zalanyi
去除字符串两端的空格。%09代表制表符(\t)。 - fred02138

5

iOS 9中:

myString = myString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!

希望这可以帮助到您。

非常感谢你,兄弟。 - Jerome

4
对于 swift3,您可以这样做:
let url = URL(string:url.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)!

3
感谢你们的帮助。 我已将以下两行代码添加到我的程序中,现在它可以正常工作了:
    selectedFeedURL = selectedFeedURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
    selectedFeedURL =  selectedFeedURL.stringByReplacingOccurrencesOfString("%09%09", withString:"")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接