url session in iOS

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.

Accepted Reply

This is not a valid URL because the curly brackets must be percent encoded. The best way to build URLs like this is to lean on

URLComponents
. I generally build a
URLComponents
value from the fixed part of the URL — stuff that I know is valid and doesn’t change between runs of my app — and then modify that value with the dynamic stuff. For example:
var uc = URLComponents(string: "http://www.carrierlookup.com/index.php/api/balance")!
uc.queryItems = [
    URLQueryItem(name: "key", value: "{145fdf639c68b4e48f53957e5f3830450fc40565}")
]
print(uc.url!)
// http://www.carrierlookup.com/index.php/api/balance?key=%7B145fdf639c68b4e48f53957e5f3830450fc40565%7D

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Replies

I figured out that the optional let url is returning a nil. How do I get my app to get a response from the latter url?

I figured out that the optional let url is returning a nil.

I presume you’re talking about lines 22 through 24 here. If so, there’s something else going on here. The only reason that

URL(string:)
can fail is that the URL is malformed, and the URL you posted in just fine. Indeed, I ran your snippet of code here in my office:
let urlString = "https://www.example.com/"

if let url = URL(string: urlString) {
    print("OK")
} else {
    print("NG")
}

and it worked as expected (printing

OK
).

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

I apologize. I was using a different version of the code that is in my post. I was using a different value for urlString. Here's what should be in line 22 of the original code in my original post:


let urlString = "http://www.carrierlookup.com/index.php/api/balance?key={145fdf639c68b4e48f53957e5f3830450fc40565}"

This is not a valid URL because the curly brackets must be percent encoded. The best way to build URLs like this is to lean on

URLComponents
. I generally build a
URLComponents
value from the fixed part of the URL — stuff that I know is valid and doesn’t change between runs of my app — and then modify that value with the dynamic stuff. For example:
var uc = URLComponents(string: "http://www.carrierlookup.com/index.php/api/balance")!
uc.queryItems = [
    URLQueryItem(name: "key", value: "{145fdf639c68b4e48f53957e5f3830450fc40565}")
]
print(uc.url!)
// http://www.carrierlookup.com/index.php/api/balance?key=%7B145fdf639c68b4e48f53957e5f3830450fc40565%7D

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Ok. Thanks.