具有基本身份验证的 iOS 快速 Web 服务调用



我试图从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()
}
这取决于

您的 Web 服务,但您需要将这些值添加到您的Request中。

例如,向标头添加值:

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

或者你可能需要在你的Request中添加一个正文:如何在 Swift 中使用 JSON 正文发出 HTTP Post 请求

我的错。我在这个问题上有点太仓促了。我回来的不是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()

相关内容

  • 没有找到相关文章

最新更新