从NSURLConnection POST方法获取数据

时间:2016-06-03 08:09:35

标签: ios objective-c iphone ios9 nsurlconnection

我已将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

2 个答案:

答案 0 :(得分:2)

这对我有用

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

答案 1 :(得分:1)

您必须使用委托方法来验证操作成功并获取返回的数据。

- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response 
{
    NSLog("@Resp received");
    return;
}

- (void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *)data 
{
    NSLog("@Data received");
    return
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error 
{
    NSLog("@ERROR: Achtung !: %@",[error localizedDescription]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH , 0),, ^{
        NSLog(@"FinishedLoading: In bg thread, do something with data here");

        dispatch_async( dispatch_get_main_queue(), ^{
            NSLog(@"FinishedLoading: In Main thread, access the UI here");
        });
    });
}