ios - 尝试重用 NSURL 时获取 Nil

标签 ios objective-c iphone swift

我正在尝试使用 https://developer.forecast.io/ 获取某些位置的天气接口(interface)。 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()

    }

最佳答案

您使用的 URL ("https://api.forecast.io/forecast/\(apiKey)/36.861941, -111.374420") 应该格式正确,并且根据 Apple 的说法,符合RFC2396 .如果不是 NSURL 将返回 nil

您使用的网址不正确。例如空格应该使用 "%20" 进行转义。对于您的情况,我认为您可以删除空格。

关于ios - 尝试重用 NSURL 时获取 Nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27613466/

相关文章:

ios - 无论IOS显示什么 View ,都能检测到从屏幕左侧滑动吗?

ios - 为什么 iOS 选择特定的亚洲字体?

iphone - 无法访问向其中传递值的 NSMutableDictionary 外部方法

iOS 应用程序发布到 iTunes Connect - 未找到应用程序记录

iphone - Objective-C for循环问题

ios - iOS 是否有断开互联网连接的事件?

Javascript RegEx 无法识别移动 iOS 上的撇号

ios - 找不到 Firebase 模块

ios - 我可以发布包含半透明项目的应用程序吗?

ios - valueForKeyPath 可以计算总和的最大值吗?