Skip to content

Instantly share code, notes, and snippets.

@hboon
Created January 28, 2018 05:34
Show Gist options
  • Save hboon/15c093ec315019919e0a9185b2312f11 to your computer and use it in GitHub Desktop.
Save hboon/15c093ec315019919e0a9185b2312f11 to your computer and use it in GitHub Desktop.
GET with NSURLSession + Basic Auth in RubyMotion
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