0

How do I create a Swift code to make API call for this curl

curl -u myusername:mypassword https://test.mysite.com?type=min

I tried this, but I don't see any successful response.... I was expecting some response printed on this line print(response)

    let urlString = "https://test.mysite.com"
    var urlComponents = URLComponents(string: urlString)
        urlComponents?.queryItems = [
            URLQueryItem(name: "type", value: "min"),
        ]
     let url = urlComponents?.url
        if let url = url {
        
        // Create URL request
        var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10.0)
        request.httpMethod = "GET"
        request.addValue("myusername:mypassword", forHTTPHeaderField: "u")        
        guard url != nil else {
            // couldn't create url
            return
        }
        
        // Create URLSession
        let session = URLSession.shared

        // Create the Data Task
        let dataTask = session.dataTask(with: request) { (data, response, error) in
            // check there is not an error
            if error == nil {
            print(response)                    
            }
        }            
        // Start the data task
        dataTask.resume()
    }
learner
  • 435
  • 3
  • 9
  • 23
  • 2
    Basic Auth token should be sent in the Authorization http header...check this tut: https://cocoacasts.com/networking-essentials-how-to-implement-basic-authentication-in-swift – RTXGamer Mar 09 '22 at 05:36
  • Read [this](https://stackoverflow.com/a/62968667/771231). You are converting the `-u` wrong. There is no such thing as `u` http header field. – Desdenova Mar 09 '22 at 06:51

0 Answers0