2014-12-03 67 views
1

我对一对坐标进行反向地理编码以找到用户所在的城市,但我很难将城市变为Motion-Kit布局。什么是让城市进入布局的最佳途径?我也会将API中的其他信息添加到布局中,以便可能会遇到同样的问题。在Motion-Kit布局中使用异步获取的数据

有一个基本的MK布局是这样的:

class HomeLayout < MK::Layout 

    def initialize(data) 
    @city = data[:city] 
    super 
    end 

    def layout 
    add UILabel, :location 
    end 

    def location_style 
    text @city 
    color :white.uicolor 
    font UIFont.fontWithName("Avenir", size: 22) 
    size_to_fit 
    center ['50%', 80] 
    end 

end 

我得到@city此方法在HomeScreen

def city 
    loc = CLLocation.alloc.initWithLatitude App::Persistence['latitude'], longitude: App::Persistence['longitude'] 
    geo = CLGeocoder.new 
    geo.reverseGeocodeLocation loc, completionHandler: lambda { |result, x| 
    return result[0].locality 
    } 
    # This currently returns a CLGeocoder object, but I want it to return the city as a String. 
end 

我得到App::Persistence['latitude']on_activate在AppDelegate中,像这样:

def on_activate 
    BW::Location.get_once do |result| 
    if result.is_a?(CLLocation) 
     App::Persistence['latitude'] = result.coordinate.latitude 
     App::Persistence['longitude'] = result.coordinate.longitude 
     open HomeScreen.new 
    else 
     LocationError.handle(result[:error]) 
    end 
    end 
end 

任何帮助将升值ated。提前致谢。

回答

2

我得看看你是如何实例化布局的,但即使没有这个我也有猜测:你应该考虑支持fetching location的消息,当数据可用的时候消除。

工作流会是这个样子:

  • 创建布局没有提供位置数据。它将开始在“等待位置”状态
  • 获取城市的位置,就像你现在
  • 提供位置的布局,它可以动画视图改变

class HomeLayout < MK::Layout def location(value) # update view locations. # you might also provide an `animate: true/false` argument, # so that you can update the UI w/out animation if the # location is available at startup end end

完成此操作后,您可以进行第二遍:启动时提供城市数据。如果数据可用,您应该能够像上面一样将它传递给初始化程序,并且布局应该绕过“加载”状态。

我推荐这种方法的原因是因为它使控制器更“幂等”。无论是否在启动时提供位置数据,它都可以处理这两种情况。

此外,在等待get_once区块完成之前,您将能够open HomeScreen.new

相关问题