Swift解析JSON函数在完成之前返回

时间:2018-07-01 03:51:43

标签: ios swift

所以,我有以下功能。

func totalEntries() -> String {
        var totalInResponse = "0"

        let urlString = "http://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findCompletedItems&SERVICE-VERSION=1.13.0" + preferences.getValue(key: "appKey") + "&GLOBAL-ID=EBAY-US&keywords=jeter&itemFilter(0).name(0)=SoldItemsOnly&itemFilter(0).value(0)=true&RESPONSE-DATA-FORMAT=JSON&paginationInput.entriesPerPage=5"

        let url = URL(string: urlString)

        let task = URLSession.shared.dataTask(with: url! as URL) {
            data, response, error in
            // Handler
            if let mydata = data {
                do {
                    let myJson = try JSONSerialization.jsonObject(with: mydata, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: AnyObject]


                    if let findCompletedItemsResponse = myJson["findCompletedItemsResponse"] as? NSArray {
                        if let findPaginationOutput = findCompletedItemsResponse[0] as? NSDictionary {
                            if let getPaginationOutput = findPaginationOutput["paginationOutput"] as? NSArray {
                                if let getPaginationOutputDirectory = getPaginationOutput[0] as? NSDictionary {
                                    //print(getPaginationOutputDirectory)
                                    if let totalEntries = getPaginationOutputDirectory["totalEntries"] as? NSArray {
                                        totalInResponse = totalEntries[0] as! String
                                        print("totalInResponse: \(totalInResponse)")
                                    }
                                }
                            }
                        }

                    }
                } catch {
                    print("Error get information: ", error)
                }
            }
        }

        task.resume()
        print("totalInResponse \(totalInResponse)")
        return totalInResponse
    }

通过调试,我发布了在打印实际总数之前此ALWAYS始终返回0。这是按此顺序返回的。

  

totalInResponse 0

     

totalInResponse:28683

这很重要,因为我需要首先检查是否有可用的条目。

我什至做了这样的事情

 let number = self.totalEntries()

        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            print(number)
        }

在显示print(number)的地方,它仍然显示0。

任何帮助解决这个问题的方法都将是惊人的。

0 个答案:

没有答案