簡體   English   中英

具有基本身份驗證的iOS快速Web服務調用

[英]iOS swift web service call with basic authentication

我為嘗試從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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM