斯威夫特5。如何等待来自另一个 .swift 文件的请求?
Swift5. How to wait the request from another .swift file?
有 2 个文件:
第 1 - 网络请求
2nd - ViewController,getCities() -> Array<String> { ... }
结果所在的位置
应该被调用(至少可以用 print
检查
使用它来发出请求:
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error as Any)
} else { ...
}
问题: 在请求完成之前,UIViewController
无法访问请求的结果。 UIViewController
的list
启动太早
P.S: 已经试过了
semaphore
和
group
但对我来说,它仅适用于相同的 class/file。
不问,说
使用完成处理程序在数据可用时发出通知。没有信号量,没有组。
func getCities(completion: @escaping ([String]) -> Void) { ... }
和
getCities { [weak self] cities in
self?.list = cities
print(cities)
// do other stuff with received cities
}
有 2 个文件:
第 1 - 网络请求
2nd - ViewController,getCities() -> Array<String> { ... }
结果所在的位置
应该被调用(至少可以用 print
使用它来发出请求:
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error as Any)
} else { ...
}
问题: 在请求完成之前,UIViewController
无法访问请求的结果。 UIViewController
的list
启动太早
P.S: 已经试过了
semaphore
和
group
但对我来说,它仅适用于相同的 class/file。
不问,说
使用完成处理程序在数据可用时发出通知。没有信号量,没有组。
func getCities(completion: @escaping ([String]) -> Void) { ... }
和
getCities { [weak self] cities in
self?.list = cities
print(cities)
// do other stuff with received cities
}