2013-05-31 36 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变量,然后可以安全地从后台线程访问该变量。

相关问题