在iphone中发布Url时,连接是否收到两次调用的数据?
我是iphone开发新手。我已经发布了带有用户名和密码的URL。我可以用“connection didReceiveData”方法打印数据。但是我看到“connection didReceiveData”方法调用了两次。我不知道我哪里出错了。这是我的密码在iphone中发布Url时,连接是否收到两次调用的数据?,iphone,url,posting,Iphone,Url,Posting,我是iphone开发新手。我已经发布了带有用户名和密码的URL。我可以用“connection didReceiveData”方法打印数据。但是我看到“connection didReceiveData”方法调用了两次。我不知道我哪里出错了。这是我的密码 - (void)viewDidLoad { [super viewDidLoad]; NSString *post = [NSString stringWithFormat:@"&domain=school.edu&user
- (void)viewDidLoad {
[super viewDidLoad];
NSString *post = [NSString stringWithFormat:@"&domain=school.edu&userType=2&referrer=http://apps.school.edu/navigator/index.jsp&username=%@&password=%@",@"xxxxxxx",@"xxxxxx"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://secure.school.edu/login/process.do"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(@"Connection Successful");
}
else
{
NSLog(@"Connection could not be made");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"the data %@",string);
}
整个HTML页面在控制台中打印了两次。因此,请帮助我。谢谢。您可能会收到分块的响应数据,这就是为什么说明: “委托应连接每个传递的数据对象的内容,以建立URL加载的完整数据。” 为此,请使用
NSMutableData
的实例,并且仅在收到-connectiondFinishLoading:
消息后才处理完整的数据。根据状态,如果以块形式接收数据,则可以多次调用connection:didReceiveData。这意味着您必须将所有块保存在某个变量中,并在ConnectiondFinishLoading方法中进行数据处理。e、 g
NSMutableData *receivedData = [[NSMutableData alloc] init];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data, for example log:
NSLog(@"data: %@", [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]
}
如果接收到大量数据,可能需要查看NSFileHandler,以便在数据块到达时将其写入磁盘。否则NSMutableData应该可以,特别是如果你不想存储数据的话。Felix,这是一个很好的观点,特别是关于iPhone有限的内存。