【发布时间】: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,您可以享受基于块的完成处理程序的简单性(有点像NSURLConnection的sendAsynchronousRequest...没有委托方法担心如果你不想),但是(a)它是可以取消的; (b) 避免使用现已弃用的NSURLConnection。 -
另外,我不清楚你为什么要麻烦继承
NSData。这通常是不必要的。通常你只需使用NSMutableData。 -
@Rob 谢谢。是的,我将使用 NSURLSession。应该先检查它是否已被弃用。
标签: ios objective-c iphone ios9 nsurlconnection