0

I am going crazy with trying to get some data (JSON) from a web service.

Can someone please tell me how I can add username and password authentication to this call? It must not be like the code below. If you have some code that work with swift 3.0 I would looove to see it.

func downloadData()
{
    let url = NSURL(string: "https://www.someurl.com")
    let request = NSMutableURLRequest(url: url! as URL)

    let task = URLSession.shared.dataTask(with: request as URLRequest) { data,response,error in
        guard error == nil && data != nil else
        {
            print("Error:",error!)
            return
        }

        let httpStatus = response as? HTTPURLResponse

        if httpStatus!.statusCode == 200
        {
            if data?.count != 0
            {
                let responseString = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary //because JSON data started with dictionary. Not an array
                let status = responseString["status"] as! String

                if status == "ok"
                {
                    print("Status is :", status)

                    //Ok, so far so good. Now let's get the data...
                }
                else
                {
                    print("Status is not Okay!")
                }
            }
            else
            {
                print("No data got from url!")
            }
        }
        else
        {
            print("error httpstatus code is :",httpStatus!.statusCode)
        }
    }
    task.resume()
}
TommyF
  • 381
  • 1
  • 7
  • 22
  • Why is this down voted? It is a totally legit question. If not there should be loads of answers with the correct approach how to solve this. – TommyF May 11 '17 at 08:39

2 Answers2

0

It will depends on your web service, but you need to add those values to your Request.

For example adding values to your headers:

let request = NSMutableURLRequest(url: url! as URL)
request.addValue("An_Authentication_String", forHTTPHeaderField: "MyField")

Or you may need to add a body to your Request: How to make HTTP Post request with JSON body in Swift

Community
  • 1
  • 1
EhTd
  • 3,260
  • 4
  • 19
  • 18
0

My bad. I was a bit too hasty on this one. It was not JSON but XML I got back. So this is the code with basic authentication if anybody is wondering...

    let config = URLSessionConfiguration.default
    let userPasswordString = "myusername:mypassword"
    let userPasswordData = userPasswordString.data(using: String.Encoding.utf8)
    let base64EncodedCredential = userPasswordData!.base64EncodedString()
    let authString = "Basic \(base64EncodedCredential)"
    config.httpAdditionalHeaders = ["Authorization" : authString]
    let session = URLSession(configuration: config)

    let url = URL(string: "theWebServiceUrl")!
    var dataString = ""

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

        if error != nil {
            print(error!.localizedDescription)
        } else {
             //this is the XML, now go to town with an XML parser
             dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as! String
        }
    })
    task.resume()
TommyF
  • 381
  • 1
  • 7
  • 22