1

我正在尝试在后台运行 -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];

完美地工作。

4

1 回答 1

2

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

_updateFromUser.text = html;

我建议在方法触发NSURLConnectionDataDelegate时利用并更新您的 UI ...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;
}

苹果文档在这里

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

EDIT2:我搞砸了......我的代表错了......忘记了iOS5中不推荐使用的那个。使用NSURLConnectionDataDelegate. 上面的答案已经解决。

于 2013-07-02T20:57:47.230 回答