swift2 从网路上下载json 令人不解的问题一问,有关task.resume()

有关 前面的程式我就不写了,我po 我一直解决不了 跟不了解的部份
我从网路上下载一段json 如下

 request.HTTPBody = try! postString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
        if error != nil {
            print("\(error)")  //為什麼這行要加slef
            return
        }
        do {
            let myJSON:AnyObject? = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
            var iCount:NSInteger = (myJSON?.count)! as NSInteger
            for var i = 0; i < iCount; i++ {
                tmpUrl = self.webURL as String + (myJSON![i]["photo"] as? String)!
               self.webPhoto.append(self.myFunc.calculateImage(UIImageView(image: UIImage(named:"1.jpg")), W: bannerW, H: bannerH))  //Question 1

            }
            print(self.webPhoto)
            print(myJSON)
        }
        catch {
            print(error)
        }
    }
    task.resume()
    print(myJSON) // question2

Question1: 如程式中question1
为什么 webPhoto 跟myfunc 都要加self.

Question2:前面打印 myJSON 或 webPhoto都是有内容的

到在 task.resum()之后

打印出来的都变成了空值
如果需要 myJSON 跟 webPhoto 要怎么写

  1. 因为你调用的地方是闭包了,需要用self来引用
  2. resume才是真正执行。 你需要在dataTaskWithRequest 的 data, response, error in 这个中间才能拿到正确的数据。