2014-12-03 26 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

相關問題