[英]dispatch_async confliction
目前,我正在开发一个聊天应用程序,我正在尝试上传图像,除了图像上载UI冻结时,其他所有操作都正常,因此异步方法应运而生,这就是我正在尝试做的事情:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
[self dismissModalViewControllerAnimated:YES];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
UIImage *image = [info objectForKey: UIImagePickerControllerOriginalImage];
NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
//[self performSelectorOnMainThread:@selector(send:) withObject:imgData waitUntilDone:YES];
[self send:imgData];
});
}
我收到此错误:
试图从主线程或网络线程以外的其他线程获取网络锁。 这可能是从辅助线程调用UIKit的结果。 现在崩溃了...
- Web线程锁
- -[UITextView setText:]
- -[HPTextViewInternal setText:]
- -[HPGrowingTextView setText:]
- -[chatViewController发送:]
- __74- [chatViewController imagePickerController:didFinishPickingMediaWithInfo:] _ block_invoke_0
- _dispatch_call_block_and_release
- _dispatch_worker_thread2
- _pthread_wqthread
- start_wqthread
我正在使用HPGrowingTextView提供一种iMessage类型的可扩展键入区域来键入消息,但是却遇到了这个问题。
我搜索了此错误
试图从主线程或网络线程以外的其他线程获取网络锁。 这可能是从辅助线程调用UIKit的结果
人们建议使用performSelectorOnMainThread
但是这种方法会再次冻结UI。
如何解决此冲突或有其他方法。
Inside [self send:imageData]
...building a url and appending hFile(imageData)
[body appendData:[NSData dataWithData:hFile]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSString *imgUrl = [NSString stringWithFormat:@"http://www.www.www/uImages/thumbs/%@",returnString];
...
上传后,将返回图像的缩略图,如果我使用[NSURLConnection sendAsynchronousRequest
得到空的缩略图,该缩略图在uitableview中显示。
当您想更改UI中的任何内容时,应在主线程上进行更改。
因此,如果要更改您拥有的HPGrowingTextView
控件的文本,可以执行以下操作:
dispatch_async(dispatch_get_main_queue(), ^{
growingTextView.text = @"Some text";
})
之所以崩溃,是因为您在主线程之外调用send。 关于这个事实,堆栈跟踪很明显。
您需要在主线程上进行这些调用。 但是,当您这样做时,您的UI当然会由于此调用而挂起...
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
从方法名称中可以明显看出,此调用是同步的,并且将阻塞直到返回结果。
因此,您需要改用异步形式。
sendAsynchronousRequest:queue:completionHandler:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.