Reputation: 2434
I have a class which is used to get data from my server. The data returned from my server is in JSON. For some reason the didReceiveData won't run at all. I have placed NSLogs inside it to test it but it doesn't do anything?
Here is my code:
+(NSJSONSerialization *) getTask:(id)task_id{
NSString *post = [NSString stringWithFormat:@"&task_id=%@", task_id];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://my-server.com/"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn){
NSLog(@"Testing");
}
return json;
}
// Log the response for debugging
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
NSLog(@"test");
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}
// Declare any connection errors
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Error: %@", error);
}
Thanks,
Peter
Upvotes: 1
Views: 425
Reputation: 539835
getTask:
is a class method, which means the self
is the class. Therefore the delegate methods must also be class methods.
But note that you cannot return the received JSON from the getTask:
method, because NSURLConnection
works asynchronously.
Upvotes: 3
Reputation: 5818
You need to start the connection. Try using the initWithRequest:delegate:startImmediately:
method:
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
or, just call the start method:
if(conn){
[conn start];
}
Upvotes: 1