SwiftUI - 发布后台线程不允许 - 在不更新UI的代码中

3

对SwiftUI不熟悉,不理解为什么第一个代码中的JSONDecoder()代码会抛出异常。

[SwiftUI] 不允许在后台线程中发布更改;请确保通过像receive(on:)这样的运算符从主线程上发布值(在模型更新时)。

我认为这并没有更新UI,那为什么会出现这种情况?

enter image description here

 do {
    // pass the request type, bearer token, and email / password ( which are sent as POST body params )
    let request = L.getRequest(requestType:"POST", token: token, email: self.username, password: self.psw)

    L.fetchData(from: request) { result in
        switch result {
        case .success(let data):
            // covert the binary data to a swift dictionary
            do {
                let response = try JSONDecoder().decode(WpJson.self, from: data)
                for (key, title) in response.allowedReadings {
                    let vimeoId = Int( key )!
                    let vimeoUri = self.buildVimeoUri(vimeoId: key)
                    self.addReadingEntity(vimeoUri: vimeoUri, vimeoId: vimeoId, title: title)
                }
                self.writeToKeychain(jwt:response.jwt, displayName: response.displayName)
                readings = self.fetchReadings()
            }
            catch {
                self.error = error.localizedDescription
            }
        case .failure(let error):
            self.error = error.localizedDescription
        }
    }
}

我尝试在 L.fetchData(from: request) { result indo-catch 中包装了一个主队列,但这并没有帮助解决问题。

DispatchQueue.main.async { [weak self] in 

以下是登陆协议,这里没有任何UI工作:

import Foundation
import SwiftUI

struct Login: Endpoint {
    var url: URL?
    init(url: URL?) {
        self.url = url
    }
}

protocol Endpoint {
    var url: URL? { get set }
    init(url: URL?)
}

extension Endpoint {
    func getRequestUrl() -> URLRequest {
        guard let requestUrl = url else { fatalError() }
        // Prepare URL Request Object
        return URLRequest(url: requestUrl)
    }
    
    func getRequest(requestType:String="POST", token:String, email:String="", password:String="") -> URLRequest {
        var request = self.getRequestUrl()
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        
        if ( "" != email && "" != password && requestType == "POST") {
            let parameters:[String:String?] =  [
                "email": email,
                "password": password
            ]
            
            // Run the request
            do {
                // pass dictionary to nsdata object and set it as request body
                request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
            } catch let error {
                print(error.localizedDescription)
            }
        }
        return request;
    }
    
    func fetchData(from request: URLRequest, completion: @escaping (Result<Data, NetworkError>) -> Void) {
        
         URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                completion(.success(data))
           } else if error != nil {
                // any sort of network failure
                completion(.failure(.requestFailed))
           } else {
                // this ought not to be possible, yet here we are
                completion(.failure(.unknown))
           }
        }.resume()
    }
}

extension URLSession {
    func dataTask(with request: URLRequest, completionHandler: @escaping (Result<(Data, HTTPURLResponse), Error>) -> Void) -> URLSessionDataTask {
        return dataTask(with: request, completionHandler: { (data, urlResponse, error) in
            if let error = error {
                completionHandler(.failure(error))
            } else if let data = data, let urlResponse = urlResponse as? HTTPURLResponse {
                completionHandler(.success((data, urlResponse)))
            }
        })
    }
}

你有没有任何想法来解决这个问题?


self.error 是什么? - Jon Shier
@Published var error: String = "" => @Published var 错误: String = "" - ServerStorm
1个回答

4

将其包装在赋值的位置

        catch {
            DispatchQueue.main.async {
             self.error = error.localizedDescription
            }
        }
    case .failure(let error):
       DispatchQueue.main.async {
          self.error = error.localizedDescription
       }
    }

谢谢@Asperi,这解决了问题。我想知道为什么这现在显示出来了,因为我已经运行了几周的代码。是因为self.error绑定在View上,因此尽管它不是直接的UI更新,它也是更新UI的绑定吗? - ServerStorm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接