Created
November 26, 2014 03:55
Revisions
-
chunlea created this gist
Nov 26, 2014 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,72 @@ class Api class << self # Init API server, with the shared client def init_server if Auth.needlogin? AFMotion::SessionClient.build_shared(BASE_URL) do session_configuration :default header "Accept", "application/json" response_serializer :json end else AFMotion::SessionClient.build_shared(BASE_URL) do session_configuration :default header "Accept", "application/json" header "X-Api-Email", Auth.email header "X-Api-Token", Auth.token response_serializer :json end end end METHODS = %w(get post).freeze # Api.post "auth/login", data do |result, error| # if result # => # end # if error # App.alert(error["title"], {cancel_button_title: "Got it!", message: error["message"]}) # end # end METHODS.each do |method| define_method method do |path, parameters=nil, *args, &block| AFMotion::SessionClient.shared.send(method, path, parameters) do |result| p result if result.success? block.call(result.object, nil) if block else if result.error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey] error_headers = result.error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey].allHeaderFields end if result.error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey] error_code = result.error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey].statusCode error_code_local = NSHTTPURLResponse.localizedStringForStatusCode(error_code) error = result.error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] end if error_code && error_code.to_s =~ /404/ # block.call(nil, "The request is not found (404).") if block block.call(nil, {"message" => "The request is not found (404)."}) if block elsif error_code && error_code.to_s =~ /4\d{2}/ error = BW::JSON.parse error message = error["errors"] = error["errors"].map { |e| if e.kind_of?(String) e else e.join(" ") end }.join(", ") block.call(nil, {"title" => error["message"], "message" => message}) if block else block.call(nil, {"message" => result.error.localizedDescription}) if block # block.call(nil, result.error.localizedDescription) if block end end end end end end end