ios - 使用 URLSession 从另一个类调用时,属性变为空

标签 ios swift nsurlsession

出于某种原因,当我尝试从另一个类访问产品数组时,它会返回空。我做错了什么,如何填充产品数组?与 do/catch 相关吗?

显示的打印语句将给出我正在寻找的内容,但是当我在调用检索方法后尝试在另一个类中使用该属性时,它会显示为空。

仅供引用,“Product”是一个附加了名称、描述等属性的结构。

private let productListUrl = URL(string: "https://api/products.json")
var products = [Product]()

func retrieveProductList() {
    if let productListUrl = productListUrl {
        URLSession.shared.dataTask(with: productListUrl) { (data, response, error) in
            if let data = data {
                do {
                    let jsonData = try JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]
                    let tempArray: Array = jsonData["products"] as! [Any]
                    for product in tempArray {
                        let newProduct = Product(json: product as! [String : Any])
                        self.products.append(newProduct!)
                    }
                    print("In ProductService: \(self.products)")
                }
                catch {
                    print("An error occured while attempting to read data")
                }
            }
        }.resume()
    }
}

最佳答案

正如 maddy 所说,这是因为 URL 调用是异步的。

你基本上有 3 个选择:

  1. 使用信号量方法并使您的retrieveProductList方法同步。

  2. 将您的类更改为具有委托(delegate)属性,您可以在 URL 请求完成时对其执行 ping 操作。

  3. 向您的retrieveProductList方法添加一个完成处理程序,该处理程序将在URL请求完成时调用。

我个人倾向于选项 3:

func retrieveProductList(completion: @escaping ([Product])->())
{
    // Right after you print the products...
    completion(self.products)
}

关于ios - 使用 URLSession 从另一个类调用时,属性变为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50537602/

相关文章:

html - iOS 8 html输入文件控件选择 "Take Photo"选项时黑屏

string - (swift) 从字符串中删除 "\"字符?

ios - 在 Swift 中将类属性添加到协议(protocol)

ios - Swift NSURL 在有效网址上给出错误

ios - 使用 UIImagePickerController 在一个 View 中选择不同的图像

ios - 如何在不检查 SignerIdentity 的情况下检测应用程序是否已被破解?

ios - UI 图像/多 View Controller

swift - UITabBar isTranslucent 添加了一个额外的 UITabBar?

swift - 异步线程的返回值

ios - 不使用 3rd 方库是否需要 URLSession 才能获取远程数据?