我在尝试从Web服务获取一些数据(JSON)时会发疯。
有人可以告诉我如何在此通话中添加用户名和密码验证吗?它不能像下面的代码。如果你有一些可以使用swift 3.0的代码,我会很乐意看到它。
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()
}
答案 0 :(得分:0)
这取决于您的网络服务,但您需要将这些值添加到Request
。
例如,为标题添加值:
let request = NSMutableURLRequest(url: url! as URL)
request.addValue("An_Authentication_String", forHTTPHeaderField: "MyField")
或者您可能需要在Request
:How to make HTTP Post request with JSON body in Swift
答案 1 :(得分:0)
我的坏。我对这个有点太仓促了。它不是JSON,而是我回来的XML。所以这是具有基本身份验证的代码,如果有人想知道......
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()