Datsik Datsik - 1 month ago 12
Swift Question

Getting an error when trying to move code from the Playground to its own file

Hi guys I'm having issues trying to get this little playground to run, I mocked this up in the Playground which works fine but I'm having issues trying to get it to run in its own

swift
file

let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "http://reddit.com/r/globaloffensive/new")!

let task = session.dataTask(with: url, completionHandler: {
(data, response, error) in

if error != nil {
print(error!.localizedDescription)
} else {
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
dump(json)
}
} catch {
print("Error")
}
}
})
task.resume()


I'm mainly trying to figure out how to make API calls, but when I run this in its own file and run

swift run test.swift
I get

test.swift:1:14: error: use of unresolved identifier 'URLSessionConfiguration'
let config = URLSessionConfiguration.default
^~~~~~~~~~~~~~~~~~~~~~~
test.swift:2:15: error: use of unresolved identifier 'URLSession'
let session = URLSession(configuration: config)
^~~~~~~~~~
test.swift:3:11: error: use of unresolved identifier 'URL'
let url = URL(string: "http://reddit.com/r/globaloffensive/new")!
^~~


Any information would be great thanks.

Answer

You need to import the Foundation framework:

import Foundation
Comments