运行后台线程不起作用

时间:2013-07-02 20:37:22

标签: objective-c

我正在尝试在后台运行-getHTMLupdate,但它无效。

-viewDidLoad

- (void)viewDidLoad {
    UIImage *navBarImage = [[UIImage imageNamed:@"menubar.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(5, 15, 5, 15)];//Navbar
    [[UINavigationBar appearance] setBackgroundImage:navBarImage forBarMetrics:UIBarMetricsDefault];

    [self performSelectorInBackground:@selector(getHTMLupdate) withObject:nil];
}

这是-getHTMLupdate

-(void) getHTMLupdate {
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    /* set headers, etc. on request if needed */
    [request setURL:[NSURL URLWithString:@"http://appstarme.com/GD/GDHTMLPARSINGINFORMATION.php"]];
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
    NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSScanner *scanner = [NSScanner scannerWithString:html];
    NSString *token = nil;
    [scanner scanUpToString:@"<h1>" intoString:NULL];
    [scanner scanUpToString:@"</h1>" intoString:&token];

    NSLog(@"DATA : %@", html);

    _updateFromUser.text = html;

这是控制台输出

   2013-07-02 20:26:25.775 Social App[8130:3707] DATA : 
Please check out the new Skype contest at www.Skype.com
2013-07-02 20:26:25.776 Social App[8130:3707] bool _WebTryThreadLock(bool), 0x1e8ab970: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...
1   0x3a021259 WebThreadLock
2   0x36083185 <redacted>
3   0xc75fd -[homeChannel getHTMLupdate]
4   0x349e7231 <redacted>
5   0x3c2170e1 <redacted>
6   0x3c216fa8 thread_start

NSLog奇怪地返回正确的数据,但应用程序仍然崩溃

修改

在代码末尾添加了

[_updateFromUser performSelectorOnMainThread: @selector(setText:)
                            withObject: html
                         waitUntilDone: FALSE];

工作得很好。

1 个答案:

答案 0 :(得分:2)

您正在崩溃,因为您尝试使用此调用更新后台线程中的UI:

_updateFromUser.text = html;

我建议利用NSURLConnectionDataDelegate并在connection:didReceiveData:方法触发时更新您的用户界面...

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
  NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  NSScanner *scanner = [NSScanner scannerWithString:html];
  NSString *token = nil;
  [scanner scanUpToString:@"<h1>" intoString:NULL];
  [scanner scanUpToString:@"</h1>" intoString:&token];

  NSLog(@"DATA : %@", html);

  _updateFromUser.text = html;
}

Apple Docs Here

编辑:我还建议您将请求更改为sendAsynchronousRequest,以免产生后台线程,并按预期利用委托方法。

EDIT2:我搞砸了......我让代表错了......忘了iOS5中哪一个被弃用了。使用NSURLConnectionDataDelegate。上述答案已得到解决。