我正在尝试实现一个异步请求。我做了研究,这是我得到的最好的结果,但代码充满了错误,我找不到解决方案
NSURL *url2 = [NSURL URLWithString:@"www.google.com"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url2];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil)
[delegate receivedData:data];//i get the error here use of undeclared identifier 'delegate' ,when I put self insead I receive the error : no visible @interface for "my class name" declares the selector "received data"
else if ([data length] == 0 && error == nil)
[delegate emptyReply];//same error here
else if (error != nil && error.code == ERROR_CODE_TIMEOUT) //the error here is "use of undelcared identifier ERROR_CODE_TIMEOUT
[delegate timedOut];//error here is save as the first one
else if (error != nil)
[delegate downloadError:error];//error here is save as the first one
}];我已经在.h文件中添加了NSURLConnectionDelegate
谁能告诉我错误是什么?
谢谢
发布于 2012-03-29 13:01:01
我对这种方法没有太多的经验,但是这个例子是有效的。我将此信息发送到我的服务器,以测试获取应用内购买的产品信息。你可以把更多的else-if放进去,就像你发布的那样,测试不同的可能结果,但这应该会让你开始。我不确定为什么您发布的存根引用了一个委托--块方法的要点(或其中一个要点)就是能够在没有委托的情况下完成这些事情。
- (void)makeConnection {
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:kServerPath]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:5];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:theRequest queue:queue completionHandler:^(NSURLResponse* theResponse, NSData* theData, NSError* error) {
NSLog(@"%@, %@ %@",theResponse.suggestedFilename,theResponse.MIMEType,theResponse.textEncodingName);
if (theData != nil && error == nil) {
NSArray *productArray = [NSJSONSerialization JSONObjectWithData:theData options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",productArray);
}else{
NSLog(@"%@",error.localizedDescription);
}
}];}
发布于 2012-03-29 11:36:13
我发现只做- initWithRequest: delegate :并在必要时实现委托方法会更容易。你会想要
- (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response和
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data至少。有关代码,请参阅http://developer.apple.com/library/ios/#samplecode/SimpleFTPSample/Listings/URLGetController_m.html。请注意,为增量块调用了did接收数据。您可能希望跟踪特性中的总数据,并在数据到达时附加数据。除此之外,您还可以添加错误处理和身份验证,但这应该是开始。
https://stackoverflow.com/questions/9918554
复制相似问题