我正在使用MVVM模式进行服务呼叫
**code:**在viewcontroller中postGenericCallVM
正在调用,响应也来了,但是print("testing viewmodel data in viewcontroller \(String(describing: postVM.postDataVM?.postCount))")
没有,为什么?
我错在哪里?
struct RequestObject {
var params: [String: Any]? = nil
var method: HTTPMethod
var urlPath: String
var isTokenNeeded: Bool
var isLoaderNeed: Bool = false
var isErrorNeed: Bool = false
var vc: UIViewController?
}
class APINetworkManager2: NSObject {
static let sharedInstance = APINetworkManager2()
fileprivate override init() {
super.init()
}
func serviceCall<T: Decodable>(requestObject: RequestObject, completion: @escaping (Result<APIResponse<T>, Error>) -> Void) {
guard let url = URL(string: requestObject.urlPath) else {
return
}
var urlRequest = URLRequest(url: url)
if requestObject.isTokenNeeded {
let token = "Bearer token" // Replace with your actual token
urlRequest.setValue(token, forHTTPHeaderField: "Authorization")
}
urlRequest.httpMethod = requestObject.method.rawValue
if let params = requestObject.params {
let paramsReq: [String: Any] = ["jsonrpc": "2.0", "params": params]
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: paramsReq)
} catch {
completion(.failure(error))
return
}
}
let task = URLSession.shared.dataTask(with: urlRequest) { data, _, error in
if let data, let string = String(data: data, encoding: .utf8) {
print("debug check \(string)")
}
do {
let response = try JSONDecoder().decode(APIResponse<T>.self, from: data!)
DispatchQueue.main.async {
completion(.success(response))
}
} catch {
DispatchQueue.main.async {
completion(.failure(error))
}
}
}
task.resume()
}
}
字符串
这是我的VIEwmodel代码这里打印o/p**result view model: model data coming
**
class PostViewModel {
var postDataVM: PostGenResult?
func postGenericCallVM(){
let param = ["page_no" : "1"] as? [String:Any]
let requestObject = RequestObject(
params: param,
method: .post,
urlPath: "https://hsfjkhskdn",
isTokenNeeded: true,
isLoaderNeed: true,
isErrorNeed: true
)
APINetworkManager2.sharedInstance.serviceCall(requestObject: requestObject) { (result: Result<APIResponse<PostGenResult>, Error>) in
switch result {
case .success(let response):
self.postDataVM = response.result as? PostGenResult
print("result view model: \(self.postDataVM)")
case .failure(let error):
print("Error decoding JSON: \(error)")
}
}
}
}
型
o/p:在viewcontroller中成功获取响应
结果视图模型:可选(PracticeCode.PostGenResult(pageCount:1,perPage:10,postCount:5,userReminder:[PracticeCode.UserReminder(id:17,receiverID:7,type:“Subscription”,message:“Your Subscription is due in 2
这是我的viewcontroller代码:这里
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
postVM.postGenericCallVM()
print("testing viewmodel data in viewcontroller \(postVM.postDataVM?.postCount)")
}
}
型
服务调用正在调用,响应即将到来,但testing viewmodel data in viewcontroller
给出零
在viewcontroller中测试viewmodel数据:nil
1条答案
按热度按时间unftdfkk1#
这是真的,因为你正在请求一个
async
任务,而postVM.postGenericCallVM()
将需要一些时间进行回调。字符串
另一方面,这些代码将同步执行。有关详细信息,您可以在此处放置日志。
型
然后你会看到打印输出顺序应该是:
型
如何处理?方法1,在
postGenericCallVM
函数中添加@escaping完成。型
方法2,使用
async await
型