2013-05-31 35 views
2

所以我希望我的應用程序在發送http請求並獲得響應時不要鎖定GUI,我做了一個嘗試,但它抱怨我在mainthread之外使用uikit,是否有人請告訴我分離http和gui的正確方法?在ios上的其他線程上運行http請求

-(void)parseCode:(NSString*)title{ 

    UIActivityIndicatorView *spinner; 
    spinner.center = theDelegate.window.center; 
    spinner.tag = 12; 
    [theDelegate.window addSubview:spinner]; 
    [spinner startAnimating]; 

    dispatch_queue_t netQueue = dispatch_queue_create("com.david.netqueue", 0); 

    dispatch_async(netQueue, ^{ 
     NSString *url =[NSString stringWithFormat:@"http://myWebService.org/"]; 
     // Setup request 
     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
     [request setURL:[NSURL URLWithString:url]]; 
     [request setHTTPMethod:@"POST"]; 
     NSString *contentType = [NSString stringWithFormat:@"application/x-www-form-urlencoded"]; 
     [request addValue:contentType forHTTPHeaderField:@"Content-Type"]; 

     NSMutableString *data = [[NSMutableString alloc] init]; 
     [data appendFormat:@"lang=%@", @"English"]; 
     [data appendFormat:@"&code=%@", theDelegate.myView.text ]; 
     [data appendFormat:@"&private=True" ]; 
     [request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]]; 
     NSHTTPURLResponse *urlResponse = nil; 
     NSError *error = [[NSError alloc] init]; 

     NSData *responseData = [NSURLConnection sendSynchronousRequest:request 
              returningResponse:&urlResponse 
                 error:&error]; 

     NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 


     dispatch_async(dispatch_get_main_queue(), ^{ 

      [spinner stopAnimating]; 
      [spinner removeFromSuperview]; 
      [self presentResults:result]; 
     }); 

    }); 

} 
+0

我沒有看到變量'spinner'在哪裏被分配。 –

回答

1

相反的,用以製造方法與NSURLConnection:initWithRequest:delegate:startImmediately:,它異步發送請求。使用NSURLConnection:connectionDidFinishLoading委託方法來處理響應。

Apple在URL Loading System Programming Guide中提供了一個示例。

如果將startImmediately設置爲YES,則委託方法將在與調用請求的方法相同的運行循環中調用。很可能,這將是您的主要運行循環,因此您可以在委託方法中修改所需的UI,而無需擔心線程問題。

1

我沒有看得多了進去,但你可以嘗試,

[self performSelectorInBackground:@selector(parseCode:) withObject: title]; 

該方法將導致在回地面一個單獨的線程運行的功能,並採取舉手之勞實施,我用它當我正在做簡單的下載,如 [NSData dataWithContentsOfURL:url];但如果你做的更大,你可能需要做更多的工作。

,如果你需要調用方法列一類的一面,那麼你將不得不在課堂上,使得然後上面說的呼叫將使用NSURLConnection:sendSynchronousRequest調用選擇

1

我不認爲問題出在你的HTTP代碼上 - 這是你在後臺線程中訪問UI的問題。具體是這條線:

[data appendFormat:@"&code=%@", theDelegate.myView.text ]; 

你假設訪問UITextView或那裏類似的東西。您需要在後臺線程之外執行此操作。將其移入本地NSString變量,然後可以安全地從後臺線程訪問該變量。

相關問題