gpt4 book ai didi

ios - 从 NSURLConnection POST 方法获取数据

转载 作者:行者123 更新时间:2023-11-28 19:37:11 24 4
gpt4 key购买 nike

我已经将 NSData 对象子类化到我的 .h 和 .m 文件中,如下所示:

@interface Test : NSData // and so forth

我创建了一个生成 JSON 数据以作为 POST 发送回服务器的函数。我在代码中找到了这一部分:

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

问题一:

我如何知道连接/发布何时完成?是在下面的if/else中吗?

if(conn) {
NSLog(@"Connection Successful");
} else {
NSLog(@"Connection could not be made");
}

问题二:

我如何使用下面的这些委托(delegate)方法来获取返回的数据?

// This method is used to receive the data which we get using post method.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data

// This method receives the error report in case of connection is not made to server.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

// This method is used to process the data after connection has made successfully.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection

最佳答案

这对我有用

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"API link"]

NSLog(@"%@",url.standardizedURL);
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
NSLog(@"balh %@",connectionError);
if (data.length > 0 && connectionError == nil)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSString * string = [[NSString alloc] initWithData:data encoding:NSStringEncodingConversionAllowLossy];
NSLog(@"%@ %@",response,string);



[self dismissViewControllerAnimated:YES completion:^{

}];
}
}];

为了检查连接,您可以在 NSURLConnection 语句之后使用此语句

 if(response){NSLog(@"Connection Established");}else{NSLog(@"Connection not established");}

关于ios - 从 NSURLConnection POST 方法获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37609228/

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