2010-03-15 44 views
11

我是iphone開發新手。我已經發布了帶有用戶名和密碼的URL。我能夠在「連接didReceiveData」方法中打印數據。但是我看到「連接didReceiveData」方法被調用兩次。我不知道,我哪裏出錯了。這裏是我的代碼連接didReceiveData在iphone中發佈Url時調用兩次?

- (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頁面兩次,所以請幫助我。謝謝。

回答

14

您可能會收到塊的響應數據,這就是爲什麼NSURLConnection's documentation狀態:

委託應串聯交付建立完整的數據的URL負載每個數據對象的內容。」

爲此,請使用NSMutableData的實例,並且只能在收到-connectionDidFinishLoading:消息後處理完整數據。

+0

如果您收到大量數據,您可能需要查看NSFileHandler,以便在磁盤到達時將塊寫入磁盤。否則NSMutableData應該沒問題,特別是如果你不想存儲數據。 – FelixLam 2010-03-15 10:37:27

+0

好點,菲利克斯 - 尤其是關於iPhone的有限內存。 – 2010-03-15 14:02:21

11

MacOS Developer Library所述,如果數據以組塊形式接收,則可以多次調用connection:didReceiveData。這意味着您必須將所有塊保存在某個變量中,並使用connectionDidFinishLoading方法執行數據處理。例如

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] 
}