Ich hatte ein paar Probleme mit Swift 3 eine URLSession mit aktivierter Authentifizierung zustande zu bekommen.
Viele Anleitungen gelten noch für Swift 2, hier mal mein Code (Am beispiel einer Json Abfrage):
let url = URL(string: "http://blublbub.com/json")!
print (url)
let config = URLSessionConfiguration.default
let username = "user"
let password = "password"
let loginData = String(format: "%@:%@", username, password).data(using: String.Encoding.utf8)!
let base64LoginData = loginData.base64EncodedString()
let authString = "Basic \(base64LoginData)"
config.httpAdditionalHeaders = ["Authorization" : authString]
let urlSession = URLSession(configuration: config)
let task = urlSession.dataTask(with: url) { (data, response, error) in
let jsonData = try! JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject]
}
}
task.resume()
Zusätzlich hier noch ein snip für HTTP Requests:
let devURL = URL(string: "http://url.com")
let username = "user"
let password = "password"
let loginData = String(format: "%@:%@", username, password).data(using: String.Encoding.utf8)!
let base64LoginData = loginData.base64EncodedString()
//HTTP Request:
let request = NSMutableURLRequest(url: devURL!)
request.httpMethod = "GET"
request.setValue("Basic \(base64LoginData)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil{
print("error=\(String(describing: error))")
return
}
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString=\(String(describing: responseString))")
}
task.resume()