I have the following code:
import Foundation
typealias CompletionHandler = () -> Void
class MySessionDelegate : NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate, URLSessionStreamDelegate {
var completionHandlers: [String: CompletionHandler] = [:]
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
print("data", data.description)
data.forEach {
word in
print(word)
}
let string = String(data: data, encoding: .utf8)
print("DATA:\n\(string)\nEND DATA\n")
}
}
let defaultConfiguration = URLSessionConfiguration.default
let ephemeralConfiguration = URLSessionConfiguration.ephemeral
let backgroundConfiguration = URLSessionConfiguration.background(withIdentifier: "com.myapp.networking.background")
let cachesDirectoryURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
let cacheURL = cachesDirectoryURL.appendingPathComponent("MyCache")
var diskPath = cacheURL.path
let cache = URLCache(memoryCapacity:16384, diskCapacity: 268435456, diskPath: diskPath)
defaultConfiguration.urlCache = cache
defaultConfiguration.requestCachePolicy = .useProtocolCachePolicy
let delegate = MySessionDelegate()
let operationQueue = OperationQueue.main
let defaultSession = URLSession(configuration: defaultConfiguration, delegate: delegate, delegateQueue: operationQueue)
let ephemeralSession = URLSession(configuration: ephemeralConfiguration, delegate: delegate, delegateQueue: operationQueue)
let backgroundSession = URLSession(configuration: backgroundConfiguration, delegate: delegate, delegateQueue: operationQueue)
let urlString = "https://www.example.com/"
if let url = URL(string: urlString) {
let dataTask = defaultSession.dataTask(with: url)
dataTask.resume()
}
It works fine when urlString equals "https://www.example.com/", but when I change urlString to "http://www.carrierlookup.com/index.php/api/balance?key={145fdf639c68b4e48f53957e5f3830450fc40565}" it doesn't work. Both urls work when I put them into a web browser, although for the second url it returns a message saying that the api key could not be found. What doe I need to do to get my code to work. The latter url returns a JSON encoded object.