【发布时间】:2018-07-23 12:41:53
【问题描述】:
我需要像这样创建 GET 请求:
https://public-api.nazk.gov.ua/v1/declaration/?q=Чер
https://public-api.nazk.gov.ua/v1/declaration/?q=Володимирович
= 之后的最后一个字符是西里尔符号
我提出这样的获取请求:
var hostURL = "https://public-api.nazk.gov.ua/v1/declaration/?q="
hostURL = hostURL + searchConditions
let escapedSearchConditions = hostURL.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
let url = URL(string: escapedSearchConditions!)!
请求是: https://public-api.nazk.gov.ua/v1/declaration/?q=%D0%9F%D1%80%D0%BE
从服务器返回必要的数据,但返回的数据无法解码。
它适用于搜索条件中的整数,但不适用于西里尔文字(
import Foundation
struct Declarant: Codable {
var id: String
var firstname: String
var lastname: String
var placeOfWork: String
var position: String
var linkPDF: String
}
struct DeclarationInfo: Codable {
let items: [Declarant]
}
导入基础
struct DeclarationInfoController {
func fetchDeclarationInfo (with searchConditions: String, completion: @escaping(DeclarationInfo?) -> Void) {
var hostURL = "https://public-api.nazk.gov.ua/v1/declaration/?q="
hostURL = hostURL + searchConditions
let escapedSearchConditions = hostURL.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
let url = URL(string: escapedSearchConditions!)!
print(url)
let dataTask = URLSession.shared.dataTask(with: url) {
(data, response, error) in
let jsonDecoder = JSONDecoder()
print("Trying to decode data...")
if let data = data,
let declarationInfo = try? jsonDecoder.decode(DeclarationInfo.self, from: data) {
completion(declarationInfo)
print(declarationInfo)
} else {
print("Either no data was returned, or data was not properly decoded.")
completion(nil)
}
}
dataTask.resume()
}
}
import UIKit
class DeclarationViewController: UIViewController {
let declarationInfoController = DeclarationInfoController()
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var resultLabel: UILabel!
@IBAction func beginSearchButton(_ sender: UIButton) {
declarationInfoController.fetchDeclarationInfo(with: searchBar.text!) { (declarationInfo) in
if let declarationInfo = declarationInfo {
DispatchQueue.main.async {
self.resultLabel.text = declarationInfo.items[0].lastname
}
}
}
}
}
【问题讨论】:
-
请显示
DeclarationInfo的定义。我得到ЧЕРАХ的代码与您显示的完全相同,只是我使用了自己的DeclarationInfo版本。 -
OOPer,使用 DeclarationInfo 更新。请看一下