NSURLSession阻止如何等待数据加载完成

时间:2016-06-16 07:57:05

标签: json swift nsurlsession completionhandler

你好我想执行一些webservice请求并返回json数组。所以我做了类似的事。

enum JSONError: String, ErrorType {
    case NoData = "ERROR: no data"
    case ConversionFailed = "ERROR: conversion from JSON failed"
}

func getData(path: String) -> (NSArray)  {
    var datalistArray = NSArray()
    let baseUrl = NSBundle.mainBundle().infoDictionary!["BaseURL"] as! String
    let fullUrl = "\(baseUrl)\(path)"

    print("FULL URL-----HTTPClient \(fullUrl)")
    guard let endpoint = NSURL(string:fullUrl) else {
        print("Error creating endpoint")
        return NSArray()
    }
    let request = NSMutableURLRequest(URL: endpoint)
    NSURLSession.sharedSession().dataTaskWithRequest(request,completionHandler: {(data,response,error) in
        do {
            guard let data = data else {
                throw JSONError.NoData
            }
            guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary else {
                throw JSONError.ConversionFailed
            }
            print(json)
            if let data_list = json["data"] as? NSArray {
                dispatch_async(dispatch_get_main_queue())
                {
                    datalistArray = data_list

                }

            }

        }catch let error as JSONError {
            print(error.rawValue)
        } catch let error as NSError {
            print(error.debugDescription)
        }





}).resume()

    return datalistArray

  }

}

但是这会在从webservice数据填充它之前returndatalistArray。之后有时它返回空数组我可以看到这个print(json)执行并打印json数据。但调用它的函数已经采用了空的返回数组。这是什么原因? 请帮我解决这个问题 感谢

更新 编辑后,这就是我调用我的Web服务的方式

func getData(path: String, completion: (dataArray: NSArray)->()) {
    //var datalistArray = NSArray()
    let baseUrl = NSBundle.mainBundle().infoDictionary!["BaseURL"] as! String
    let fullUrl = "\(baseUrl)\(path)"

    print("FULL URL-----HTTPClient \(fullUrl)")
    guard let endpoint = NSURL(string:fullUrl) else {
        print("Error creating endpoint")
        return
    }
    let request = NSMutableURLRequest(URL: endpoint)
    NSURLSession.sharedSession().dataTaskWithRequest(request) {(data,response,error) in
        do {
            guard let data = data else {
                throw JSONError.NoData
            }
            guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary else {
                throw JSONError.ConversionFailed
            }
            print(json)
            if let data_list = json["data"] as? NSArray {
               // dispatch_async(dispatch_get_main_queue())
               // {
                    completion(dataArray: data_list)

                //}

            }

        }catch let error as JSONError {
            print(error.rawValue)
        } catch let error as NSError {
            print(error.debugDescription)
        }





}.resume()



 }

在我ViewController这就是我的呼唤。我不是直接调用httpclient类方法

func vw_getCategories()
{
    api.getAllCategories(){ (dataArray) in

            self.vw_allCategories=dataArray as! [Category]
        print("----CATEGORIES----\(self.vw_allCategories)")
        }
}

在我的api班级

func getAllCategories(completion: (dataArray1: NSArray)->())
{
    persistencyManager.getCategories("tvcategory.php") { (dataArray) in

        self.categories=dataArray as! [Category]

    }
    completion(dataArray1: self.categories)
}

在这个persistencymanager类里面调用像这样的httpclient方法。

func getCategories(path: String,completion: (dataArray: NSArray)->())
{
    httpClient.getData(path)
    {
        (dataArray) in for datadictionary in dataArray
            {
                let cat = Category.init(term_id: datadictionary["term_id"] as! String, name: datadictionary["name"] as! String, slug: datadictionary["slug"] as! String)
                self.categories.append(cat)
            }
    }


    completion(dataArray: self.categories)
}

请您检查一下,让我知道问题出在哪里,我该如何解决。

0 个答案:

没有答案