【发布时间】:2014-02-05 22:31:48
【问题描述】:
我有一个已经工作了一段时间的 NSURLConnection 突然不工作了。
由于某种原因,唯一被调用的委托方法是:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:
没有调用其他委托方法。我有其他类使用几乎相同的代码,只是不同的请求和 url,它们似乎都工作正常。我已经阅读了很多关于确保连接与委托等在同一个线程上的帖子,但似乎对我没有任何用处。我知道服务器正在返回响应,因为如果我通过一个简单的 html 表单传递相同的信息,我会在浏览器中得到响应,并且我可以看到服务器端脚本正在运行的证据,因为我可以看到它所做的更改SQL 数据。并且应用程序正在获得某种响应,它只是没有获取任何数据或调用 connectionDidFinishLoading 委托方法。
对可能出现的问题有什么想法吗?
这是我的代码的简化版本:
#import "RegistrationViewController.h"
@interface RegistrationViewController ()
@end
NSMutableData *responseData;
NSURLConnection *theconnection;
@implementation RegistrationViewController
/*
* Attempt to Register online. Returns False if valiation failed
*/
- (BOOL) registerOnline{
// OTHER CODE HERE TO BUILD DATA FOR THE REQUEST
// URL Request
NSURL *requestUrl = [NSURL URLWithString:THEURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:requestUrl];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
// Initialse Response Object
responseData = [[NSMutableData alloc] init];
// Conection
theconnection = [NSURLConnection connectionWithRequest:request delegate:self];
[theconnection start];
return YES;
}
/*
* Handle the event of registration failing
*/
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"didFailWithError");
// OTHER CODE HERE TO HANDLE THE ERROR....
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"did receive response ");
}
/*
* Handle the reciept of Data
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"didReceiveData");
// Add data to the response
[responseData appendData:data];\
}
/*
* Data finnished loading
*/
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"connectionDidFinishLoading");
// OTHER CODE HERE TO HANDLE THE RESPONSE....
}
【问题讨论】:
-
顺便说一句,您是否使用
CFURLCreateStringByAddingPercentEscapes对bodyData中捕获的值进行了百分比转义?另外,如果bodyData是一个字符串,[request setHTTPBody:[bodyData dataUsingEncoding:NSUTF8StringEncoding]]。 -
是的,我正在这样做,只是没有在上面显示它,因为我认为没有必要。我确信服务器正在成功接收我的请求数据。
标签: objective-c nsurlconnection