2015-04-17 56 views
0

我在從網站向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); 
            } 
           }]; 

    }); 

}); 

} 
+0

好的,這裏有更多的信息。我只是改變了以下行:NSLog(@「datalength is%ld」,[self.connectionData length]);到NSLog(@「datalength is%ld」,[data length]);事實證明,completionHandler中的*數據對象確實收到了完整的數據。這個問題似乎發生在將數據放入self.connectionData期間(這是一個NSMutableData對象,在.h文件中定義) – PaulLian

回答

0

你不初始化self.connectionData。所以,你需要在開頭的以下部分:

if (!self.connectionData) { 
    self.connectionData = [[NSMutableData alloc] init]; 
} 
+0

謝謝,Man!但是,請給我一個非常虛擬的問題,爲什麼我仍然需要啓動這self.connectionData?我以爲系統啓動它自動,因爲它是在.h文件中定義.... – PaulLian

+0

@PaulLian屬性是由實例變量支持,所以他們必須像任何其他變量一樣初始化。訪問器方法的屬性會自動合成,您可以查看[Encapsulating Data](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html)以獲取詳細信息。 – VolenD