Web服务返回零

时间:2019-07-12 14:44:30

标签: swift

我无法使用从Web服务获取的returnHTML数据填充UITextField。

如果我的网络服务如下:

import Foundation;
class WebSessionCredentials {
    static let requestURL = URL(string:"xxxx.on.ca/getData.aspx?requestType=Tech")!
    var htmlbody: String?
    var instancedTask: URLSessionDataTask?
    static var sharedInstance = WebSessionCredentials()
    init() {
        self.instancedTask = URLSession.shared.dataTask(with: WebSessionCredentials.requestURL) { [weak self] (data,response,error) in
            if let error = error {
                // Error
                print("Client Error: \(error.localizedDescription)")
                return
            }
            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                print("Server Error!")
                return
            }
            guard let mime = response.mimeType, mime == "text/html" else {
                print("Wrong mime type!");
                return
            }

            if let htmlData = data, let htmlBodyString = String(data: htmlData, encoding: .utf8) {
                self?.htmlbody = htmlBodyString;
            };
        };
    };
};

通过这个,我应该能够通过WebSessionCredentials.sharedInstance.htmlbody;

访问返回的HTML响应。

在操场上验证这一点,我似乎在类中得到了正确的响应,但是当从类外部调用htmlbody时,我得到的响应为零-关于如何发送从中获得的HTML字符串,我的想法不完整类到函数之外。这个问题是基于我几天前发布的另一个问题-> Delegating privately declared variables to a public scope

谢谢

编辑添加的图片 Image of myPlayground

1 个答案:

答案 0 :(得分:1)

不是在dataTask方法中实现init,而是添加带有完成处理程序的方法run

class WebSessionCredentials {

    enum WebSessionError : Error {
        case badResponse(String)
    }

    static let requestURL = URL(string:"xxxx.on.ca/getData.aspx?requestType=Tech")!
    static var sharedInstance = WebSessionCredentials()

    func run(completion : @escaping (Result<String,Error>) -> Void) {
        let instancedTask = URLSession.shared.dataTask(with: WebSessionCredentials.requestURL) { (data,response,error) in
            if let error = error {
                // Error
                print("Client Error: \(error.localizedDescription)")
                completion(.failure(error))
                return
            }
            guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
                completion(.failure(WebSessionError.badResponse("Server Error!")))
                return
            }
            guard let mime = response.mimeType, mime == "text/html" else {
                completion(.failure(WebSessionError.badResponse("Wrong mime type!")))
                return
            }
            completion(.success(String(data: data!, encoding: .utf8)!))
        }
        instancedTask.resume()
    }
}

并使用

WebSessionCredentials.sharedInstance.run { result in
    switch result {
    case .success(let htmlBody): print(htmlBody)
    case .failure(let error): print(error)
    }
}