2014-02-26 26 views
1

我有一個類用於從我的服務器獲取數據。從我的服務器返回的數據是JSON。出於某種原因,didReceiveData根本無法運行。我已經將NSLog放入它來測試它,但它沒有做任何事情?爲什麼didReceiveData函數不能正常工作

這裏是我的代碼:

+(NSJSONSerialization *) getTask:(id)task_id{ 

    NSString *post = [NSString stringWithFormat:@"&task_id=%@", task_id]; 

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
    NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]]; 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://my-server.com/"]]]; 
    [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(@"Testing"); 
    } 

    return json; 
} 

// Log the response for debugging 
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data { 
    NSLog(@"test"); 
    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; 
    json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil]; 
} 

// Declare any connection errors 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
    NSLog(@"Error: %@", error); 
} 

感謝,

彼得

+0

請注意,您*無法*從'getTask:'方法返回接收到的JSON,因爲NSURLConnection *異步*工作。 - 也許你從'getTask:'返回後取消連接? –

+0

我不確定。那麼我怎樣才能把NSURLConnection放在一個類中呢? –

+0

因爲上面的代碼會在我的應用程序中多次使用,這就是爲什麼我將它放在類中 –

回答

3

getTask:是一個類的方法,這意味着self是類。因此委託方法也必須是類方法。

但請注意,您不能從getTask:方法返回收到的JSON,因爲NSURLConnection異步工作。

+0

謝謝,這有其他方法的工作。現在我只需要知道如何返回最初調用該類的UIViewController的json變量。 –

+1

@PeterStuart:無法阻止當前線程,無法使異步方法同步。 - 通常的方法是'connectionDidFinishLoading'用接收到的數據回調視圖控制器。還要注意''didReceiveData:'可能會被大量數據調用。 –

+0

我不確定你的意思?你有這方面的任何文件可以幫助嗎? –

1

你需要開始連接。嘗試使用initWithRequest:delegate:startImmediately:方法:

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES]; 

,或者只是調用start方法:

if(conn){ 
    [conn start]; 
} 
+1

我認爲這不能解釋它。根據文檔,'initWithRequest:delegate:'相當於調用'initWithRequest:delegate:startImmediately:'並將'YES'傳遞給'startImmediately'。 –

+0

我有這個代碼在其他地方使用,它會自動啓動它,但這是我第一次在類中使用它,這可能是爲什麼。我會回報。謝謝 –

+0

我試過這兩種方法,沒有什麼作用? –

相關問題