我知道這已在很多其他帖子中討論過,但我需要發佈它,因爲這些線程不幸我不幸幫助我。我試圖連接到返回響應GET request.I JSON格式的一些數據的軌服務器已經實現了NSConnectionDataDelegate四種方法如下面列出NSURL代表didReceiveData方法不叫
#pragma mark -
#pragma mark NSURLConnectionDataDelegate
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"didReceiveResponse");
[resultData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"didReceiveData");
[resultData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"didFailWithError");
NSString *errDesc = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
NSLog(@"%@",errDesc);
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"didReceiveLoading");
}
在connectionDidFinishDownloading方法(未上市)我執行JSON解析,但由於從未調用過didReceiveData方法,因此resultData爲空。
didReceiveResponse方法被調用,因爲我看到消息被記錄。服務器正在本地主機上運行,所以我可以確認收到請求並使用Charles我知道響應以JSON格式正確接收。所以在服務器端似乎沒有問題。但didReceiveData方法永遠不會被調用。 didFailWithError方法都不是。
是否有人可以幫助我?我無法弄清楚我做錯了什麼。這是我第一次與NSURL合作,所以非常感謝。我正在使用ARC在iOS 5上工作。
薩蒂揚
編輯:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?%@", kDevelopmentMode ? kLocalHost : kHost, endpoint, parameters]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
嗨我試着你的建議,我得到原始數據和json數據打印到日誌中的預期。但我不明白我的NSURLRequest有什麼問題。你有什麼建議嗎?我已將我的請求代碼添加爲編輯。謝謝! – Satyam 2012-02-09 11:24:17
我猜你在我給你的代碼中使用了這個URL:NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@「%@%@?%@」,kDevelopmentMode? kLocalHost:kHost,端點,參數]];如果你做到了,那麼你的url和你的json數據是好的。我將在編輯中提供我的代碼。看看是否適合你。 – Jaybit 2012-02-09 16:10:20
我意識到我做錯了什麼。我已經實現了NSURLConnectionDownloadDelegate的didFinishDownloading方法,因爲我認爲這將是在收到所有數據時調用的方法。當我從類定義中刪除委託並刪除方法時,所有方法都按預期工作。你的回答讓我想知道爲什麼我要實施didFinishLoading和其他方法。謝謝!! – Satyam 2012-02-09 17:16:57