json MVVM模式服务调用响应未进入Swift中的ViewController

9rygscc1  于 12个月前  发布在  Swift
关注(0)|答案(1)|浏览(101)

我正在使用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

unftdfkk

unftdfkk1#

这是真的,因为你正在请求一个async任务,而postVM.postGenericCallVM()将需要一些时间进行回调。

//Will execute on background thread
APINetworkManager2.sharedInstance.serviceCall

字符串
另一方面,这些代码将同步执行。有关详细信息,您可以在此处放置日志。

print("Requesting")
postVM.postGenericCallVM()
print("testing viewmodel data in viewcontroller \(postVM.postDataVM?.postCount)")


然后你会看到打印输出顺序应该是:

Requesting

testing viewmodel data in viewcontroller \(postVM.postDataVM?.postCount)

result view model: \(self.postDataVM)


如何处理?方法1,在postGenericCallVM函数中添加@escaping完成。

func postGenericCallVM(completion: @escaping (() -> Void)) {
    ...
    switch result {
        ...
    }
    completion()
}

postVM.postGenericCallVM { [weak self] in
    //TODO: Re-check postVM.postDataVM here
}


方法2,使用async await

func postGenericCallVM() async {
    await withCheckedContinuation { continuetion in
    ...
        APINetworkManager2.sharedInstance.serviceCall {
            ...
            continuetion.resume(returning: ())
        }
    }
}

Task {
    await postVM.postGenericCallVM()
    print("\(postVM.postDataVM)")
}

相关问题