NSURLSession.sharedSession()。dataTaskWithRequest在函数中运行缓慢

时间:2016-05-18 18:47:35

标签: ios arrays json swift nsurlsession

当我想将mysql数据库中的数据填充到类对象中时,我的问题出现了。我试图返回一个对象数组,它返回nil然后它以某种方式填充自己。如何在返回空白数组之前填充它?

这是我的代码和代码输出的屏幕截图

import Foundation

class Research
{
  var mainResearchImageURL:String = ""
  var userProfileImageURL:String = ""
  var caption:String = ""
  var shortDescription:String = ""

  init(mainResearchImageURL :String, userProfileImageURL:String, caption:String, shortDescription:String)
  {

    self.mainResearchImageURL = mainResearchImageURL
    self.userProfileImageURL = userProfileImageURL
    self.caption = caption
    self.shortDescription = shortDescription
  } 

  class func downloadAllResearches()->[Research]
  {
    var researches = [Research]()
    let urlString = "http://localhost/test/index.php"
    let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
    request.HTTPMethod = "POST"
    let postString = "action=listresearches"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error in
        if (error == nil) {

            do {
                let json =  try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
                //let dictionary = json!.firstObject as? NSDictionary

                var counter:Int = 0;
                for line in json!{
                    let researchData = line as! NSDictionary
                    let researchLineFromData = Research(mainResearchImageURL: researchData["research_mainImageURL"] as! String, userProfileImageURL: researchData["research_creatorProfileImageURL"] as! String, caption: researchData["research_caption"] as! String, shortDescription: researchData["research_shortDescription"] as! String)
                   researches.append(researchLineFromData) //researches bir dizi ve elemanları Research türünde bir sınıftan oluşuyor.

                    counter += 1
                    print ("counter value \(counter)")
                    print("array count in loop is = \(researches.count)")
                }
            }catch let error as NSError{
                print(error)
            }
        } else {
            print(error)
        }})
    task.resume()

    print("array count in return is = \(researches.count)")
    return researches
  }
}

这是输出:

enter image description here

2 个答案:

答案 0 :(得分:0)

在completionHandler上添加它(如果你更新视图,它会起作用)

dispatch_async(dispatch_get_main_queue(), {
    if (error == nil) { ...... }
})

建议1:

返回任务并在方法中使用完成参数, 如果任务太慢,你可以取消它。

建议2: 使用alamofire和swiftyJson框架

答案 1 :(得分:0)

这里发生的是你在完成之前返回值(记住调用是异步的),你可以做这样的事情:

class func downloadAllResearches(success:([Research])->Void,failure:(String)->Void)
{
    var researches = [Research]()
    let urlString = "http://localhost/test/index.php"
    let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
    request.HTTPMethod = "POST"
    let postString = "action=listresearches"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error in
    if (error == nil) {

        do {
            let json =  try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
            //let dictionary = json!.firstObject as? NSDictionary

            var counter:Int = 0;
            for line in json!{
                let researchData = line as! NSDictionary
                let researchLineFromData = Research(mainResearchImageURL: researchData["research_mainImageURL"] as! String, userProfileImageURL: researchData["research_creatorProfileImageURL"] as! String, caption: researchData["research_caption"] as! String, shortDescription: researchData["research_shortDescription"] as! String)
               researches.append(researchLineFromData) //researches bir dizi ve elemanları Research türünde bir sınıftan oluşuyor.

                counter += 1
                print ("counter value \(counter)")
                print("array count in loop is = \(researches.count)")
            }
            success(researches)
        }catch let error as NSError{
            print(error)
            failure("Can be extract from NSERROR")
        }
    } else {
        print(error)
        failure("Error - Can be extract for NSERROR")
    }})
task.resume()

}

为了打电话,这个功能使用这样的东西:

    Research.downloadAllResearches({ (objects:[Research]) -> Void in
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //Do whatever you like with the content
        })
    }) { (failureLiteral:String) -> Void in

    }