Skip to content

Instantly share code, notes, and snippets.

@alloy
Created March 24, 2011 14:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alloy/885125 to your computer and use it in GitHub Desktop.
Save alloy/885125 to your computer and use it in GitHub Desktop.
MacRuby NSURLConnection example.
framework 'AppKit'
class Download
attr_reader :response, :responseBody
def start(request)
puts "START!"
NSURLConnection.connectionWithRequest(request, delegate:self)
end
def connection(connection, didReceiveResponse:response)
@response = response
@downloadData = NSMutableData.data
end
def connection(connection, didReceiveData:data)
@downloadData.appendData(data)
end
def connectionDidFinishLoading(connection)
case @response.statusCode
when 200...300
@responseBody = NSString.alloc.initWithData(@downloadData, encoding:NSUTF8StringEncoding)
puts "Downloaded: #{@responseBody}"
when 300...400
puts "TODO: Handle redirect!"
else
puts "Oh noes, an error occurred: #{@response.statusCode}"
end
NSApplication.sharedApplication.terminate(self)
end
end
# GET request:
#
request = NSMutableURLRequest.requestWithURL(NSURL.URLWithString("http://eekthecat.8m.com/"))
# POST request:
#
# postBody = "Current status: Kumbaya!"
# request.setHTTPMethod("POST")
# request.setHTTPBody(postBody.dataUsingEncoding(NSUTF8StringEncoding))
d = Download.new
d.start(request)
NSApplication.sharedApplication.run
@alloy
Copy link
Author

alloy commented Mar 24, 2011

This is async. A sync call is even easier, you just need to use: http://bit.ly/efASex

@alloy
Copy link
Author

alloy commented Mar 24, 2011

Run this example from the command-line. To use the code in an application, remove the messages sent to NSApplication#sharedInstance.

@colevoss
Copy link

This works great and it returns the data that i am looking for. Only I canoot seem to access the data from anywhere but the connectionDidFinishLoading.

How might I get the data from there

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