public
Last active

MacRuby NSURLConnection example.

  • Download Gist
NSURLConnection.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
 
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

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

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

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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.