我似乎无法在JSONDecoder块内的任何地方访问struct成员。我如何在其他地方访问这些api返回值,例如在可以在任何地方调用并返回api数据的函数中。最后一行超出范围或不允许。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
struct ObjectLookup: Codable {
let ObjectID: Int?
let ObjectName: String?
let Creators: String?
let Medium: String?
let Titles: String?
let LabelUUID: String?
static func fetch(withID id : String){
let urlString = DomainURL + "\(id)"
print("urlString is \(urlString)" )
if let url = URL(string: urlString) {
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data,response,error) in
print(String(data: data!,encoding: .ascii) ?? "no data")
if let ObjectLookup = try? JSONDecoder().decode(ObjectLookup.self, from: data!) {
print( ObjectLookup.ObjectName ?? "no url")
}
})
task.resume()
}else{
print("bad url")
}
}
}
ObjectLookup.fetch(withID: "2322A63C74C92")
let myName = ObjectLookup.ObjectName
}
答案 0 :(得分:1)
将其重构为此
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
ObjectLookup.fetch(withID: "2322A63C74C92") { obj in
print(obj?.ObjectName)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
}
struct ObjectLookup: Codable {
let ObjectID: Int?
let ObjectName: String?
let Creators: String?
let Medium: String?
let Titles: String?
let LabelUUID: String?
static func fetch(withID id : String,completion:@escaping(_ ret:ObjectLookup?) -> Void ){
let urlString = DomainURL + "\(id)"
print("urlString is \(urlString)" )
if let url = URL(string: urlString) {
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data,response,error) in
print(String(data: data!,encoding: .ascii) ?? "no data")
if error != nil {
compeltion(nil)
return
}
if let res = try? JSONDecoder().decode(ObjectLookup.self, from: data!) {
print( res.ObjectName ?? "no url")
completion(res)
}
})
task.resume()
}else{
print("bad url")
completion(nil)
}
}
}
不要大写变量名的第一个字母使用camelCase(仅对类使用),我知道更改任何字母都会破坏编码过程,因此请记住它或使用CodingKeys转换变量,也请注意URLSession.shared.dataTask
的回调在后台队列中,因此请考虑使用
DispatchQueue.main.async {}
如果要执行任何UI操作,请在viewDidLoad
中进行内部回调