SWIFT: Why is “NSURL(string:” returning with Nil,

2019-02-17 13:29发布

The first two example links are working the third one returns NIL.

Why is NSUrl returning nil for such string, even though it's a valid url in a browser?

Am I supposed to process the string more?

Here is my code:

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
    }
  }
}

Any suggestions?

4条回答
劳资没心,怎么记你
2楼-- · 2019-02-17 13:41

In iOs 9:

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

Hope it helps

查看更多
做个烂人
3楼-- · 2019-02-17 13:43

For swift3 you can do like this

let url = URL(string:url.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)!
查看更多
我命由我不由天
4楼-- · 2019-02-17 13:43

Thank you guys for your help. I added these two lines to my code and it works now:

    selectedFeedURL = selectedFeedURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
    selectedFeedURL =  selectedFeedURL.stringByReplacingOccurrencesOfString("%09%09", withString:"")
查看更多
老娘就宠你
5楼-- · 2019-02-17 13:50

You should URL-encode the URL like this:

selectedFeedUrl = selectedFeedUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

查看更多
登录 后发表回答