更新:顯然,在iOS 5上,問題在於「分塊編碼」,發送時沒有一切正常。似乎在服務器上,出於某種原因在iOS 5上的傳輸永遠不會結束(在iOS 6上一切正常)。任何人都有辦法解決這個問題?在iOS 5中使用NSURLConnection無法正常工作
我使用NSURLConnection的這完美的作品在iOS 6上同一版本的模擬器,但是測試,在較早的設備,當我得到響應,只有
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
,且從未
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
假設包含我的相關數據。
下面是我用我用過的所有功能代碼的片段(我看到一些人消除一些委託功能解決了類似的問題,但對我來說,我沒有他們):
-(void)establishConnection{
NSURL *url;
url = .... // Here I've set my url - it's https
self.responseData = [[NSMutableData alloc] initWithLength:0] ;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:SERVER_RESPONSE_TIMEOUT];
[request setHTTPMethod:@"POST"];
// More settings here //
....
//Accept-Language: ENUS
[request addValue:@"ENUS" forHTTPHeaderField:@"Accept-Language"];
// "Accept-Topic: Dictation"
[request addValue:@"Dictation" forHTTPHeaderField:@"Accept-Topic"];
// "Accept: text/plain"
[request addValue:@"text/plain" forHTTPHeaderField:@"Accept"];
//"Transfer-Encoding: chunked"
[request addValue:@"chunked" forHTTPHeaderField:@"Transfer-Encoding"];
NSMutableData *postBody = [NSMutableData data];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [NSString stringWithFormat:@"%@",[paths objectAtIndex:0]]; // Get sound directory
NSData *soundData = [NSData dataWithContentsOfFile: [NSString stringWithFormat:@"%@/%@",documentsDirectory, @"rec.wav"]];
[postBody appendData:soundData];
[postBody appendData:[@"\r\n" dataUsingEncoding: NSUTF8StringEncoding]];
// final boundary
//[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
// add body to post
[request setHTTPBody:postBody];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// You may have received an HTTP 200 here, or not...
NSLog(@"didReceiveResponse");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString* aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"This is my first chunk %@", aStr);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connectionV {
connectionV = nil;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Something went wrong...");
}
請幫助我找不到我做錯了什麼。
您在didReceiveResponse中收到200嗎? –
不,我得到400.因爲https,iOS5有什麼不同嗎?它適用於iOS 6 ... 我發送兩個完全相同的參數。 – Idan
似乎問題與iOS 5上的「分塊編碼」有關。請檢出我的更新。 – Idan