如何依次下载和处理2套数据? [英] How to download and process 2 sets of data, one after the other?

查看:71
本文介绍了如何依次下载和处理2套数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在打电话进行网络服务以获取数据列表.在获得所有这些数据之后,我想针对该列表中的每个项目进行网络通话.这是我到目前为止的代码:

I am making a webservice call to get a list of data. After I have all of that data I would like to make a web call for every item on that list. Here is the code I have this far:

let zipcde:String = self.zipCode
  let username:String = "tr1gger"
  //webservice call
  var listZip = [String]()
  let wsUrl: NSURL = NSURL(string: "http://api.url.org/findNearbyTheseCodesJSON?postalcode=" + zipcde + "&maxRows=100&country=US&radius=25&username=" + username)!

  let task = NSURLSession.sharedSession().dataTaskWithURL(wsUrl, completionHandler: { (data, response, error) -> Void in
    //will happen when task is complete

    if let urlContent = data {
      let jsonObject = JSON(data: urlContent)

      if let jsonDict:JSON = jsonObject["postalCodes"]{
        let postalCode = "postalCode"
        for var i:Int = 0; i < jsonDict.count; i++ {
          print("Property: \"\(jsonDict[i][postalCode])\"")
          listZip.append(String(jsonDict[i][postalCode]))
        }


        self.showLoadingMessage()
        self.listOfZips = listZip
        self.getStores()

      }
    }

  })
  task.resume()

self.getStores是一个函数,该函数开始for循环并为第一个列表中的每个项目调用一个Web服务:

the self.getStores is a function that begins a for loop and calls a webservice for every item on the first list:

func getStores(){

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {

  for areaCode in self.listOfZips{

    let url = NSURL(string: "http://myUrl.thisPlace.net/getStores.php?zipcode=" + areaCode + "&ammoType=" + self.aType)!

    let task2 = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data2, response2, error2) -> Void in

      if let jsonObject2: NSArray = (try? NSJSONSerialization.JSONObjectWithData(data2!, options: NSJSONReadingOptions.MutableContainers)) as? NSArray{
        var storeName = [String]()
        var storeAddress = [String]()
        var storeId = [String]()
        var ammoStId = [String]()
        var ammoStock = [String]()
        var ammoPrice = [String]()

        for obj in jsonObject2{
          if let name: String = obj["storeName"] as? String{
            storeName.append(name)
            storeAddress.append((obj["storeAddress"] as? String)!)
            storeId.append((obj["storeId"]as? String)!)
          }
          else if let id: String = obj["storeId"] as? String{
            ammoStId.append(id)
            ammoStock.append((obj["ammoStock"] as? String)!)
            if let priceTemp: String = obj["ammoPrice"] as? String{
              ammoPrice.append(priceTemp)
            }
          }
        }
        var storeList = [StoreItem]()
        for var index:Int = 0; index < storeId.count; ++index{
          let sId = storeId[index]
          for var i:Int = 0; i < ammoStId.count; ++i{
            let aId = ammoStId[i]
            if sId == aId{
              //creating object
              let storeItem:StoreItem = StoreItem()
              storeItem.setAddress(storeAddress[index])
              storeItem.setName(storeName[index])
              storeItem.setId(Int(storeId[index])!)
              storeItem.setAmmoStock(Int(ammoStock[i])!)
              storeItem.setAmmoPrice(ammoPrice[i])
              storeList.append(storeItem)
            }
          }
        }
        self.storeListFinal.appendContentsOf(storeList)
      }

      self.myAlert.dismissViewControllerAnimated(true, completion: nil)
      self.tableView.reloadData()

    })

    task2.resume()
  }
})

如您所见,在此呼叫结束时,我正在填充一个表.此代码大约需要18-20秒才能完成.在我的android版本上,大约需要2秒钟.我该如何优化呢?

As you can see I am populating a table at the end of this call. This code takes about 18-20 seconds to finish. On my android version it takes like 2 seconds. How can I optimize this?

感谢您的帮助.

推荐答案

在后台线程中调用UI更新(重新加载表)可能会导致延迟.因此,您应该将UI更新代码移至主线程:

Invoke UI update (reload table) in background thread can cause delay. So, you should move the UI update code to main thread:

let task2 = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data2, response2, error2) -> Void in

      ....

      dispatch_async(dispatch_get_main_queue(), {
          self.myAlert.dismissViewControllerAnimated(true, completion: nil)
          self.tableView.reloadData()
      })

    })

上面的这种方式可以暂时解决您的问题,但是,由于您在循环中创建了许多任务,因此它将多次重载表.您应该考虑另一种方法来改善这一点.

This way above can temporary solve your problem, but, it will reload you table many times because you create many tasks in loop. You should think another way to improve this.

这篇关于如何依次下载和处理2套数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆