Created
November 26, 2014 03:55
-
-
Save chunlea/f9b6ce6ee8c2c60bcf6a to your computer and use it in GitHub Desktop.
If you want to use AFMotion with status code and errors, try this file.
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 characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
7个end连续... ,分多几个方法出来看起来会更优雅些:)