Alamofire:使用JSON的数据更新数组的值

时间:2015-11-14 16:49:29

标签: arrays json swift alamofire

尝试使用JSON的数据更新struct数组时遇到问题。这是我的代码:

这是结构的定义方式: Struct

class Players::WorkoutsController < ApplicationController
   before_action :set_measurable_summary

   #...

   private
     def set_measurable_summary
       @measurable_summary = @player.measurable_summary
     end
end

这里我尝试更新数组,但它不起作用: Code

struct Shot {
    var title: String
    var desc: String
    var img: String

    init(title: String, desc: String, img: String) {
      self.title = title
      self.desc = desc
      self.img = img
    }
  }

问题是在执行函数后,数组保持无效。怎么了? 谢谢。

1 个答案:

答案 0 :(得分:0)

在假设您调用此方法的情况下工作如下:

authDribbble()
print("my data: \(self.data)") // Prints empty array.

问题在于Alamofire异步执行请求。也就是说,当您的代码进入下一行(print语句)时,工作尚未完成。您需要实现回调机制。一种方法是将函数作为authDribbble()函数的参数传递。这会将功能改为:

  func authDribbble(completion: () -> Void) {
    // create the url
    // create parameters
    Alamofire.request(.GET, url!, parameters: params)
      .responseJSON { response in

        guard let  JSON = response.result.value as? [[String : AnyObject]] else {
          // Wrong type in JSON response. 
          print(response.result.error)
        }
        self.data = JSON.map { dict in
          guard let title = dict["title"] as? String,
                     desc = dict["description"] as? String,
                      img = dict["images"] as? String else {
            // Handle error creating Shot from JSON
          }
          return Shot(title: title, desc: desc, img: img)
        }
        completion()

      }
    }
  }

然后,您将authDribbble()的调用替换为:

authDribbble() {
   print("data: \(self.data)") // Prints populated array.
}