gpt4 book ai didi

ios - 为什么 didReceiveData 函数不起作用

转载 作者:行者123 更新时间:2023-12-01 18:15:45 25 4
gpt4 key购买 nike

我有一个类用于从我的服务器获取数据。从我的服务器返回的数据是 JSON。由于某种原因, didReceiveData 根本不会运行。我已将 NSLogs 放入其中进行测试,但它什么也没做?

这是我的代码:

+(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);
}

谢谢,

彼得

最佳答案

getTask:是一个类方法,表示 self是类。因此委托(delegate)方法也必须是类方法。

但请注意,您无法从 getTask: 返回接收到的 JSON。方法,因为 NSURLConnection异步工作。

关于ios - 为什么 didReceiveData 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22051715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com