我在從網站向iOS設備檢索數據時遇到問題。網絡使用php文件從mySQL數據庫讀取一些數據。然後它以json格式發回數據。從php/json服務中獲取NSURLRequest(異步)的數據
我正在使用以下代碼來接收數據。代碼放入viewDidLoad中。爲了避免在不等待Web響應的情況下執行與UI相關的代碼,我將NSURLRequest/NSURLConnection操作放入與GCD的異步隊列中。儘管如此,控制檯窗口顯示的是NSLog,即self.connectionData沒有數據。
該結果與我直接將NSURLRequest/NSURLConnection操作直接放入viewDidLoad函數的結果相同。你知道這裏有什麼問題,爲什麼我無法獲得數據?
當我直接從瀏覽器運行php時,web服務運行良好。
非常感謝!
問候, 保羅
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
dispatch_sync(concurrentQueue, ^{
NSString *urlAsString = @"http://www.myexamplesite.com/loadProgram.php";
NSURL *url=[NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0F];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue: queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if ([data length]>0 && connectionError == nil) {
[self.connectionData appendData:data];
NSLog(@"datalength is %ld", [self.connectionData length]);
NSString *retString = [[NSString alloc] initWithData:self.connectionData encoding:NSUTF8StringEncoding];
NSLog(@"json returned: %@ <end>", retString);
}
else if ([data length]==0 && connectionError ==nil)
{NSLog(@"Nothing was downloaded!");
}
else if (connectionError != nil){
NSLog(@"Error happend = %@", connectionError);
}
}];
});
});
}
好的,這裏有更多的信息。我只是改變了以下行:NSLog(@「datalength is%ld」,[self.connectionData length]);到NSLog(@「datalength is%ld」,[data length]);事實證明,completionHandler中的*數據對象確實收到了完整的數據。這個問題似乎發生在將數據放入self.connectionData期間(這是一個NSMutableData對象,在.h文件中定義) – PaulLian