2017-01-23 90 views
1

如何使用基本身份驗證在json中獲取數據?我想從我的示例代碼中顯示字典中的數據,該怎麼做?在swift中獲取基本身份驗證的請求3

 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) 

回答

0

不完全確定這是否是您要找的。但是,當你得到迴應,你可以試試這個:

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

打印(JSON)

+0

值是零 – ibmot

+0

你得到的是零響應?打印時,響應對象的外觀如何? – Wazza

0

我建議在的URLRequest代替使用Alamofire。這裏是一個請求的例子:

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]