在swift 3中获取基本身份验证请求

时间:2017-01-23 11:54:53

标签: swift xcode swift3

如何使用基本身份验证获取json中的数据?我想从我的示例代码中显示字典中的数据,怎么做?

     let username = "user"
     let password = "pass"

     let loginString = String(format: "%@:%@", username, password)
     let loginData = loginString.data(using: String.Encoding.utf8)!
     let base64LoginString = loginData.base64EncodedString()

     // create the request
     let url = URL(string: "http://xxx.xxx.xxx.com:111/customer")!
     var request = URLRequest(url: url)
     request.httpMethod = "GET"
     request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

     // fire off the request
     // make sure your class conforms to NSURLConnectionDelegate
     let urlConnection = NSURLConnection(request: request, delegate: self)

2 个答案:

答案 0 :(得分:0)

不完全确定这是否是您正在寻找的。但是当你收到回复时,你可以试试这个:

let json = try JSONSerialization.jsonObject(with: responseObject as! Data, options: .mutableContainers) as? [String: Any]

打印(JSON)

答案 1 :(得分:0)

我建议使用Alamofire代替URLRequest。以下是请求的示例:

 let headers: HTTPHeaders = ["Authorization": defaults.string(forKey: "apiKey")!]

    Alamofire.request("https://../getBeacons", method: .get, headers: headers)
        .responseJSON { (responseObject) -> Void in

            if responseObject.result.isSuccess {
                let resJson = JSON(responseObject.result.value!)
                print(resJson)
                for (_, subJson) in resJson["data"] {
beaconData.id.append(subJson["id"].intValue)
beaconData.id.append(subJson["min"].intValue)
beaconData.id.append(subJson["maj"].intValue)

}
            }
            if responseObject.result.isFailure {
                let error : Error = responseObject.result.error!
                print(error)
            }
    }

}

在顶部创建一个包含数组的结构,该结构将保存从Web服务接收的数据。

 struct beaconData {
    static var id = [Int]()
    static var maj = [Int]()
    static var min = [Int]()
}

您可以使用以下方式检索数据:

beaconData.id[index]