I'm currently experimenting with the twitter streaming api and i'm trying to get a stream with NSURLConnection
. As it doesn't work with twitter, i simplified everything and tried to get some source-code out of google's website, but this doesn't work neither.
The connection starts and ends, but without calling the didReceiveData
delegate. I'm sure i'm missing something. Hope you guy's can help me!
In the header: @interface ViewController : UIViewController <NSURLConnectionDataDelegate, NSURLConnectionDelegate, NSURLConnectionDownloadDelegate, NSURLAuthenticationChallengeSender>
And in the body:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURLConnection *connection;
NSMutableURLRequest *request;
// Do any additional setup after loading the view, typically from a nib.
request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.google.com"]];
[request setHTTPMethod:@"GET"];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL {
NSLog(@"Stream finished.");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", dataString);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"Connection failed!");
}
Your NSURLConnection local variable
connection
is going out of scope at the end ofviewDidLoad
. Add a property to your ViewController to hold the NSURLConnection variable in scope.A couple of thoughts.
Your declaration of
connectionDidFinishLoading
doesn't look right. The standardNSURLConnectionDataDelegate
method does not have adestinationURL
parameter:Given the presence of
NSURLAuthenticationChallengeSender
, if you're expecting a challenge (which you won't get with Google web site) then you'd obviously handle it accordingly:By the way, you do not want to call
start
method when you useinitWithRequest
orconnectionWithRequest
. It's only needed if you do a simpleinitWithRequest:delegate:startImmediately:
and instruct it to notstartImmediately
.Anyway, I used the following and it works fine:
Someone said here that it was their SOAP format NSURLConnection delegate method: didReceiveData not called ...Why ?? (iPhone SDK)
This also may be what you are looking for NSURLConnection didReceiveData not called