尝试重用NSURL时获取Nil

时间:2014-12-23 02:57:22

标签: ios objective-c iphone swift

我正在尝试使用https://developer.forecast.io/ api获取某些地点的天气。 API调用的格式为https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE

我可以从一个位置得到回复,但当我尝试更改位置并再次使用NSURL时,NSURL返回Nil。为什么这样以及如何处理?

任何人都可以帮助我吗?感谢。

func getCurrentWeatherData() -> Void {
        let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/")
        var forecastURL = NSURL(string: "36.107728,-112.113040", relativeToURL: baseURL)
        let sharedSession = NSURLSession.sharedSession()
        let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: {
            (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in

            //var urlContents = NSString(contentsOfURL: location, encoding: NSUTF8StringEncoding, error: nil)
            if (error == nil) {
                let dataObject = NSData(contentsOfURL: location)
                let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
                let currentWeather = Current(weatherDictionary: weatherDictionary)

                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.iconView.image = currentWeather.icon!
                    self.currentTimeLabel.text = "At \(currentWeather.currentTime!) it is"
                    self.temperatureLabel.text = "\(Double(currentWeather.temperature-32) * 0.56)"
                    self.summaryLabel.text = "\(currentWeather.summary)"
                    self.refreshActivityIndicator.stopAnimating()
                    self.refreshActivityIndicator.hidden = true
                    self.refreshButton.hidden = false
                })
            } else {
                let networkIssueController = UIAlertController(title: "Error", message:"Unable to load data. Connectivity error!", preferredStyle: .Alert)
                let okButton = UIAlertAction(title: "OK", style: .Default, handler:nil)
                networkIssueController.addAction(okButton)
                let cancelButton = UIAlertAction(title:"Cancel", style: .Cancel, handler:nil)
                networkIssueController.addAction(cancelButton)
                self.presentViewController(networkIssueController, animated: true, completion: nil)
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.refreshActivityIndicator.stopAnimating()
                    self.refreshActivityIndicator.hidden = true
                    self.refreshButton.hidden = false
                })
            }
        })
        downloadTask.resume()

        var forecastURL2 = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/36.861941, -111.374420")
        let sharedSession2 = NSURLSession.sharedSession()
        **//forcastURL2 returns Nil**
        let downloadTask2: NSURLSessionDownloadTask = sharedSession2.downloadTaskWithURL(forecastURL2!, completionHandler: {
            (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in

            //var urlContents = NSString(contentsOfURL: location, encoding: NSUTF8StringEncoding, error: nil)
            if (error == nil) {
                let dataObject = NSData(contentsOfURL: location)
                let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
                let currentWeather = Current(weatherDictionary: weatherDictionary)

                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.iconView2.image = currentWeather.icon!
                    self.temperatureLabel2.text = "\(Double(currentWeather.temperature-32) * 0.56)"
                    self.summaryLabel.text = "\(currentWeather.summary)"
                    self.refreshActivityIndicator.stopAnimating()
                    self.refreshActivityIndicator.hidden = true
                    self.refreshButton.hidden = false
                })
            } else {
                let networkIssueController = UIAlertController(title: "Error", message:"Unable to load data. Connectivity error!", preferredStyle: .Alert)
                let okButton = UIAlertAction(title: "OK", style: .Default, handler:nil)
                networkIssueController.addAction(okButton)
                let cancelButton = UIAlertAction(title:"Cancel", style: .Cancel, handler:nil)
                networkIssueController.addAction(cancelButton)
                self.presentViewController(networkIssueController, animated: true, completion: nil)
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.refreshActivityIndicator.stopAnimating()
                    self.refreshActivityIndicator.hidden = true
                    self.refreshButton.hidden = false
                })
            }
        })
        downloadTask2.resume()

    }

2 个答案:

答案 0 :(得分:3)

您使用的网址("https://api.forecast.io/forecast/\(apiKey)/36.861941, -111.374420")应格式正确,并且根据Apple的规定,请遵守RFC2396。如果不是NSURL将返回nil

您使用的网址不正确。例如,应使用"%20"转义空格。在你的情况下,我认为你可以删除空间。

答案 1 :(得分:-1)

删除空格:

var forecastURL2 = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/36.861941,-111.374420")

此外,对于将来的问题,如果您没有在您的方法中发布所有代码,而只是重现问题所需的代码(在这种情况下,只需要这一行是必要的) 。)