我已经将NSData对象细分为我的.h和.m文件,如下所示:

@interface Test : NSData // and so forth


我创建了一个函数,该函数生成JSON数据以POST的形式发送回服务器。我在代码的这一部分:

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


问题1:

如何知道连接/发布的时间?在下面的if / else中吗?

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


问题2:

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

// 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");}

08-18 14:54
查看更多