User-Agent in URLSession

How does one set the User-Agent header field before initiating a URLSession? I need to write an app that looks like a request is from a macOS.

@stevewebber. Thanks very much for your question!

From whatever little I know, playing with User-Agent is never a good idea.

See HTTPAdditionalHeaders

sessionConfiguration.HTTPAdditionalHeaders = ["User-Agent": "Your User Agent"]

I found the following answer on StackOverflow that I believe answers your question.

I also found the following link on YouTube that might also be of help.

:slight_smile:

I hope this helps!

All the best!

Apparently my problem was something else. I am trying to scan the HTML I get back from a URL but when I use a “GET” or a “POST” to read the HTML I receive some intermediate page.

The code I tried was:

    let sessionConfiguration = URLSessionConfiguration()
    sessionConfiguration.httpAdditionalHeaders = ["User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3"]
    let session = URLSession.shared
    let url = URL(string: "https://www.greyoakscc.com/default.aspx?p=MemProfile&id=8416150&ssid=318032&vnf=1")
    let request = NSMutableURLRequest(url: url!)

    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (data, response, error) -> Void in

        var usedEncoding = String.Encoding.utf8 // Some fallback value
        if let encodingName = response?.textEncodingName {
            let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName as CFString))
            if encoding != UInt(kCFStringEncodingInvalidId) {
                usedEncoding = String.Encoding(rawValue: encoding)
            }
        }
        if let myString = NSString(data: data!, encoding: usedEncoding.rawValue) {
            print("this is my string: \(myString)")
        } else {
            print("failed to decode data")
        }
    })
    task.resume()

When I use the URL above in a browser and then look at the source returned it is what I want, but when I look at the HTML returned from the code above it is not. I am very puzzled.

This topic was automatically closed after 166 days. New replies are no longer allowed.