Created
January 28, 2018 05:34
-
-
Save hboon/15c093ec315019919e0a9185b2312f11 to your computer and use it in GitHub Desktop.
GET with NSURLSession + Basic Auth in RubyMotion
This file contains 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
def session_with_basic_auth | |
return @session_with_basic_auth if @session_with_basic_auth | |
configuration = NSURLSessionConfiguration.defaultSessionConfiguration.tap do |conf| | |
any_username_will_do = 'xxx' | |
userPasswordString = "#{any_username_will_do}: #{api_key}" | |
userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding) | |
base64EncodedCredential = userPasswordData.base64EncodedStringWithOptions(0) | |
authString = "Basic #{base64EncodedCredential}" | |
#TODO test error handling when authorization is invalid, or when URL is wrong | |
conf.HTTPAdditionalHeaders = {'Accept'=>'application/json', | |
'Accept-Language'=>'en', | |
'Authorization'=> authString, | |
'User-Agent'=> user_agent} | |
end | |
@session_with_basic_auth = NSURLSession.sessionWithConfiguration(configuration) | |
@session_with_basic_auth.delegate = self | |
@session_with_basic_auth | |
end | |
def get_example(aURLString, &block) | |
task = session_with_basic_auth.downloadTaskWithURL(NSURL.URLWithString("#{url_prefix_v3}#{aURLString}"), completionHandler: proc {|data_url, response, error| | |
data = NSData.dataWithContentsOfURL(data_url) | |
handle_api_result(data, error, &block) | |
}) | |
task.resume | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment