Skip to content

Instantly share code, notes, and snippets.

Created Dec 4, 2016
What would you like to do?
Pythonista, NSMutableURLRequest with a GET request. Using headers, parameters and ios basic authentication.
# python
from urlparse import urlparse
from urllib import urlencode
from ctypes import c_void_p
import json
import base64
# pythonista
import objc_util
class Requests(object):
def __init__(self): = None
def get(self, url=None, auth=None, headers=None, params=None):
# Make url
if params:
params_encoded = urlencode(params)
params_encoded = ""
url = objc_util.nsurl("{}?{}".format(url, params_encoded))
#request = objc_util.ObjCClass("NSURLRequest").request(URL=url)
request = objc_util.ObjCClass('NSMutableURLRequest').alloc().initWithURL_(url)
# Make headers
if headers:
for key in headers:
request.setValue_forHTTPHeaderField_(headers[key], key)
if auth:
userName, password = auth
authStr = "%s:%s"%(userName, password)
authencode = base64.b64encode(bytes(authStr))
request.addValue_forHTTPHeaderField_("Basic %s"%authencode, "Authorization")
configuration = objc_util.ObjCClass("NSURLSessionConfiguration").defaultSessionConfiguration()
session = objc_util.ObjCClass("NSURLSession").session(Configuration=configuration)
completionHandler = objc_util.ObjCBlock(self.responseHandlerBlock, restype=None, argtypes=[c_void_p, c_void_p, c_void_p, c_void_p])
dataTask = session.dataTask(Request=request, completionHandler=completionHandler)
# Wait for completions
wait = True
while wait:
if != None:
wait = False
return json.loads(
def responseHandlerBlock(self, _cmd, data, response, error):
if error is not None:
error = objc_util.ObjCInstance(error)
response = objc_util.ObjCInstance(response)
data = objc_util.ObjCInstance(data) = objc_util.nsdata_to_bytes(data)
#url = ""
#params = {"json" : {"first" : "lukas", "last" : "kollmer"}}
#headers = None
#auth = None
#url = ''+'/locations/'+'4'+'/vouchers'
#params = {"limit" : "4"}
#headers = {'sn-apikey': APIKEY}
#auth = None
url = ''+'/locations/'+'4'+'/vouchers.json'
params = {"limit" : "4"}
headers = None
auth = (APIKEY, "x")
data = Requests().get(url=url, auth=auth, headers=headers, params=params)
print data
print type(data)
print "Done"
Copy link

tlinnet commented Dec 4, 2016

And this should be changed:
dataTask = session.dataTaskForRequest_completion_(request, completionHandler)

Copy link

tlinnet commented Dec 4, 2016

And this
session = objc_util.ObjCClass("NSURLSession").sessionWithConfiguration_(configuration)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment