Bubblewrap HTTP - >表视图;方法返回bubblewrap查询而不是响应数据

时间:2012-08-06 15:51:08

标签: ruby rubymotion

我正在尝试Rubymotion,似乎无法想象如何完成看似简单的任务。

我为人们的目录设置了一个UITableView。我创建了一个返回json的rails后端。

Person模型定义了一个get_people类方法:

def self.get_people
  BubbleWrap::HTTP.get("http://myapp.com/api.json") do |response|
    @people = BW::JSON.parse(response.body.to_str)
    # p @people prints [{"id"=>10, "name"=>"Sam"}, {etc}] to the console
  end
end

在directory_controller中,我只想将@data的实例变量设置为我的端点返回的数组,以便我可以填充表视图。

我正在尝试在viewDidLoad中执行@data = Person.get_people,但是收到一条错误消息,指示正在传递BW响应对象:#{1}} count'for #BubbleWrap :: HTTP :: Query: 0x8d04650 ...> (NoMethodError)`

因此,如果我在BW响应块之后将我的数组硬编码到get_people方法中,一切正常。但我发现通过BW响应块的关闭我也无法持久保存实例变量。

undefined method

我在这里缺少什么?如何从bubblewrap的响应对象中获取这些数据并将其传递给可用的表单以传递给我的控制器?

2 个答案:

答案 0 :(得分:3)

正如BW文档中所解释的那样“BW :: HTTP包含NSURLRequest,NSURLConnection和朋友为Ruby开发人员提供了一个更熟悉且更易于使用的API .API使用异步调用和块来保持尽可能简单。“

由于呼叫的异步特性,在您的第二个片段中,您在实际更新之前打印@people。正确的方法是在解析结束后将新数据传递给UI(比如@ table.reloadData(),如果@people数组应该显示在UITableView中)。

以下是一个例子:

def get_people
    BubbleWrap::HTTP.get("http://myapp.com/api.json") do |response|
        @people  = BW::JSON.parse(response.body.to_str)
        update_result()
    end
end

def update_result()
    p  @people
    # do stuff with the updated content in @people
end

通过RubyMotion async programming with BubbleWrap

更详细的解释,找到更复杂的用例

答案 1 :(得分:0)

就个人而言,我会跳过BubbleWrap,并采用类似的方式:

def self.get_people
  people = []
  json_string = self.get_json_from_http
  json_data = json_string.dataUsingEncoding(NSUTF8StringEncoding)
  e = Pointer.new(:object)
  hash = NSJSONSerialization.JSONObjectWithData(json_data, options:0, error: e)
  hash["person"].each do |person| # Assuming each of the people is stored in the JSON as "person"
    people << person
  end
  people # @people is an array of hashes parsed from the JSON
end

def self.get_json_from_http
  url_string = ("http://myapp.com/api.json").stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
  url = NSURL.URLWithString(url_string)
  request = NSURLRequest.requestWithURL(url)
  response = nil
  error = nil
  data = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error: error)
  raise "BOOM!" unless (data.length > 0 && error.nil?)
  json = NSString.alloc.initWithData(data, encoding: NSUTF8StringEncoding)
end
相关问题