Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Weather App with Swift (Retired) Pulling Data From the Web Making a Network Call

Pierre Smith
Pierre Smith
11,842 Points

I keep getting value of optional type 'nsurl?' not unwrapped when NSData dataWithContentsOfURL:option:error: is used

import UIKit

class ViewController: UIViewController {

private let apiKey = "d0454418a440c7bac837ee42b7e80e0a" let location = "43.854359,-79.085962" let location2 = "37.8267,-122.423"

override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib.

let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/")
let forecastURL = NSURL(string: "37.8267,-122.423", relativeToURL: baseURL)

let weatherData = NSData.dataWithContentsOfURL(forecastURL, options: nil, error: nil)

println(weatherData)

}

2 Answers

From a different thread. There are at least two problems one is that the forecastURL is an optional (that goes to nil)that need to be unwrapped and dataWithContentsOfURL is no longer working in the current Xcode. ''' class ViewController: UIViewController {

private let apiKey = ""
private let locationPoints = "40.524757, -74.471325"

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let baseURL = NSURL(string:"https://api.forecast.io/forecast/\(apiKey)/")

    let encodedPoints = locationPoints.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! // This method returns an optional, we need to force unwrap

    let forecastURL = NSURL(string: encodedPoints, relativeToURL: baseURL)

    let weatherData = NSData(contentsOfURL: forecastURL!, options: nil, error: nil)


    println(weatherData)

}

'''

Pierre Smith
Pierre Smith
11,842 Points

This is a long shot but do you know why it was removed?

Bernard Paulet
Bernard Paulet
3,364 Points

Thanks a lot! I had the same problem, could not solve it without your post!

Andres Oliva
Andres Oliva
7,810 Points

Try adding a ! sign after forecastURL in the line of weatherData.

Like this:

let weatherData = NSData.dataWithContentsOfURL(forecastURL!, options: nil, error: nil)