简体   繁体   English

从类返回NSURLConnection数据

[英]Return NSURLConnection data from class

I have am NSURLConnection to get a JSON value from my web server. 我有NSURLConnection可以从我的Web服务器获取JSON值。 The code is placed in a class which can be called from other UIViewControllers. 该代码放置在可以从其他UIViewControllers调用的类中。

I am a little unsure on how to return the JSON data from the class however. 我不确定如何从该类返回JSON数据。

Here is what I have tried: +(NSJSONSerialization *) getTask:(id)task_id{ 这是我尝试过的:+(NSJSONSerialization *)getTask:(id)task_id {

    NSJSONSerialization *json;

    NSLog(@"task 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://www.iampeterstuart.co.uk/todo/index.php/task/get"]]];
    [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 startImmediately:YES];

    [conn start];

    return json;
}

// Log the response for debugging
+ (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"Resonse: %@", response);
}
+ (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}

// Declare any connection errors
+ (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error: %@", error);
}

Each time the variable json is null? 每次变量json为空?

Could somebody please advice? 有人可以请教吗?

Many thanks, 非常感谢,

Peter 彼得

You are thinking incorrectly about the delegate's behavior. 您正在错误地考虑委托的行为。

(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data will be called whenever new data is available (downloaded from the server), which is the raw bytes of the byte stream. 只要有新数据可用(从服务器下载),便会调用(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data ,这是字节流的原始字节。 You should have an instance of NSMutableData and append that received data to the mutable data when data is received. 您应该有一个NSMutableData实例,并在接收到数据时将接收到的数据附加到可变数据中。 Finally, when the whole data (eg JSON string in your example) is downloaded, -(void)connectionDidFinishLoading:(NSURLConnection *)connection will be called. 最后,当下载全部数据(例如您的示例中的JSON字符串)时,将调用-(void)connectionDidFinishLoading:(NSURLConnection *)connection In that method, you should parse the JSON string: 在该方法中,您应该解析JSON字符串:

NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSJSONSerialization *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];

...where data is the cumulative data received. ...其中data是接收到的累积数据。 You can create the data instance as below in the class implementation: 您可以在类实现中如下创建数据实例:

NSMutableData *cumulativeData;

In init or whatever method that is initially called on your delegate before you start loading, call: init或开始加载之前在委托上最初调用的任何方法中,请调用:

cumulativeData = [NSMutableData data];

Then in your (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data method, call: 然后在您的(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data方法中,调用:

[cumulativeData appendData:data];

That should append the received data into the cumulative data that you are "building". 那应该将接收到的数据附加到您正在“构建”的累积数据中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从nsurlconnection委托方法返回响应数据 - Return Response data from nsurlconnection delegate method 如果从connection:willSendRequest:redirectResponse返回nil,为什么NSURLConnection停止发送数据: - Why does NSURLConnection stop sending data if you return nil from connection:willSendRequest:redirectResponse: NSURLConnection从重定向的URL获取数据 - NSURLConnection get data from redirected URL 将数据从NSURLConnection追加到NSMutableData对象失败 - Appending data from an NSURLConnection to an NSMutableData object fails 使用TableView中显示的NSURLConnection从服务器获取数据 - getting data from server with NSURLConnection showing in TableView 从NSURLConnection POST方法获取数据 - Getting data from a NSURLConnection POST method 使用阻塞或类似方法从NSURLConnection获取数据 - Getting data from NSURLConnection using blocking or similar 使用从NSURLConnection检索的数据填充UITableView - Populate a UITableView with data retrieved from a NSURLConnection 无法解析来自NSURLConnection响应的JSON数据 - unable to parse JSON data from a NSURLConnection response 如果需要委托函数,如何直接返回由NSURLConnection加载的数据? - How to return data directly which was loaded by NSURLConnection if delegate functions are needed?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM