Created
March 24, 2011 14:16
-
-
Save alloy/885125 to your computer and use it in GitHub Desktop.
MacRuby NSURLConnection example.
This file contains hidden or 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
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 |
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is async. A sync call is even easier, you just need to use: http://bit.ly/efASex