【问题标题】:Getting data from a NSURLConnection POST method从 NSURLConnection POST 方法获取数据
【发布时间】:2016-06-03 08:09:34
【问题描述】:

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

问题 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

【问题讨论】:

  • 顺便说一句,如果您使用NSURLSession,您可以享受基于块的完成处理程序的简单性(有点像NSURLConnectionsendAsynchronousRequest ...没有委托方法担心如果你不想),但是(a)它是可以取消的; (b) 避免使用现已弃用的 NSURLConnection
  • 另外,我不清楚你为什么要麻烦继承NSData。这通常是不必要的。通常你只需使用NSMutableData
  • @Rob 谢谢。是的,我将使用 NSURLSession。应该先检查它是否已被弃用。

标签: ios objective-c iphone ios9 nsurlconnection


【解决方案1】:

这对我有用

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我是否像 [_theData appendData] 一样从 didRecieveData 返回数据?然后在我的 if (conn) 循环中使用 _theData?
    • @cdub - 是的,didReceiveData 应该附加到 NSMutableData,但你在 connectionDidFinishLoading 中处理它,而不是回到你实例化 NSURLConnection 的位置。
    【解决方案3】:

    设置 HTTP 方法(POST 或 GET)。按照您的代码中的方式编写这些行。

    [request setHTTPMethod:@"POST"]; 
    

    【讨论】:

      猜你喜欢
      • 2012-10-24
      • 1970-01-01
      • 2015-10-22
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-08
      相关资源
      最近更新 更多