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!

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 Creating a URL

Can anyone help me out here??

why is my variable not working?

import Foundation

let courseID = "25"

let treehouseBaseURL = NSURL(string: "https://api.teamtreehouse.com/")
let courseURL = NSURL(string: courseID, relativeToURL: treehouseBaseURL)

2 Answers

Stone Preston
Stone Preston
42,016 Points

you are on the right track. the base URL is https://api.teamtreehouse.com/

to obtain info on a course, you use a URL that looks like this: https://api.teamtreehouse.com/course/someCourseID where some courseID is an actual courseID

so the base URL is https://api.teamtreehouse.com/ and the full URL needs to look like https://api.teamtreehouse.com/course/someCourseID. we can construct the full course URL using the NSURL(string: relativeToURL:)method.

we have a course ID variable with a value of 25. we can interpolate that onto the end of the string "course/" to make the second half of the url. we can pass the baseURL in as the relativeToURL argument to build the complete URL that looks like https://api.teamtreehouse.com/course/25

import Foundation

let courseID = 25
let treehouseBaseURL = NSURL(string: "https://api.teamtreehouse.com/")
let courseURL = NSURL(string: "course/\(courseID)", relativeToURL: treehouseBaseURL)

for more information on NSURL and its initalizers, see the NSURL class reference

to learn more about using interpolation in Swift, see the Swift eBook

let courseURL = NSURL(string: "course/" + String(courseID), relativeToURL: treehouseBaseURL)