我正在尝试使用uiimage-from-animated-gif将一些GIF加载到我的UITableView单元格中.但问题是,每当我尝试从我的Cache加载图像时,单元格在滚动之前会暂停一点.
这是我正在使用的代码
postGif = (UIImageView *)[cell viewWithTag:104];
if ([[ImageCache sharedImageCache] DoesExist:post[@"gif"]] == true)
{
image = [[ImageCache sharedImageCache] GetImage:post[@"gif"]];
postGif.image = [UIImage animatedImageWithAnimatedGIFData:image];
}else
{
dispatch_queue_t backgroundQueue = dispatch_queue_create("cacheImage", 0);
dispatch_async(backgroundQueue, ^{
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:post[@"gif"]]];
dispatch_async(dispatch_get_main_queue(), ^{
// Add the image to the cache
[[ImageCache sharedImageCache] AddImage:post[@"gif"] image:imageData];
NSIndexPath* ind = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
[self.feedTableView beginUpdates];
[self.feedTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:ind] withRowAnimation:UITableViewRowAnimationNone];
[self.feedTableView endUpdates];
});
});
}
postGif.layer.cornerRadius = 2.0;
postGif.layer.masksToBounds = YES;
[cell.contentView addSubview:postGif]; …Run Code Online (Sandbox Code Playgroud) 由于某种原因,我有一个dispatch_async线程,它崩溃,除非我有一个NSLog()方法在它前面执行.该块运行一个从数据库中检索用户名的方法.
崩溃:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
user_web_communicator *usrWeb = [[user_web_communicator alloc]init];
NSString *author = [usrWeb getUsernameFromID:author_string];
[_author_label setText:[NSString stringWithFormat:@"Author: %@",author]];
});
Run Code Online (Sandbox Code Playgroud)
工作:
NSLog(@"Fetching author for id: %@",author_string);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
user_web_communicator *usrWeb = [[user_web_communicator alloc]init];
NSString *author = [usrWeb getUsernameFromID:author_string];
[_author_label setText:[NSString stringWithFormat:@"Author: %@",author]];
});
Run Code Online (Sandbox Code Playgroud)
错误
Run Code Online (Sandbox Code Playgroud)2013-08-19 13:56:06.149 Poll Me[4995:c07] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '{行:AsyncImageView:0x827aa00.minX == 10 + 1*0x827b8d0.marker + -1*0x8281210.marker + 0.5*0x8281260.marker AsyncImageView:0x827aa00.minY == 27.5 + -1*0x827b910.marker + -1*0x82812a0. marker + 0.5*0x82812e0.marker + 0.5*0x82823f0.marker …
我正在使用文件夹/文件应用程序,用户可以在其中将文件下载到本地磁盘。每当用户下载文件时,我都想显示一个显示进度的下载栏。
为此,我创建了一个协议,该协议允许我的下载类和视图控制器进行通信:
协议:
protocol DownloadResponder : class {
func downloadFinished()
func downloadProgress(current:Int64, total:Int64)
}
Run Code Online (Sandbox Code Playgroud)
下载类:
class fileDownloader: NSObject, NSURLSessionDelegate, NSURLSessionDownloadDelegate {
//responder
var responder : MyAwesomeDownloadResponder?
init(responder : MyAwesomeDownloadResponder) {
self.responder = responder
}
...
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
println("downloaded \(100*totalBytesWritten/totalBytesExpectedToWrite)")
responder?.downloadProgress(totalBytesWritten, total: totalBytesExpectedToWrite)
}
...
}
Run Code Online (Sandbox Code Playgroud)
然后在我的视图控制器中,我有一个触发downloadProgress功能的下载按钮:
func downloadProgress(current:Int64, total:Int64) {
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
// do some task
var currentProgress = 100 * current …Run Code Online (Sandbox Code Playgroud) 我有以下代码,我一直试图从swift 2转换为swift 3.这是我到目前为止所拥有的.
DispatchQueue.async(group: DispatchQueue.global(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),execute: {
self.controllerDelegate?.codeToRun(progressWindowViewController: self)
})
Run Code Online (Sandbox Code Playgroud)
我收到一个错误,指出无法使用类型(int,int)的参数列表调用'global'.我知道全局队列需要这个,除非他们在swift 3中改变它吗?在Swift 3中执行全局队列的正确方法是什么?
以前的Swift 2 Equivlent
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),{
self.controllerDelegate?.codeToRun(self)
})
Run Code Online (Sandbox Code Playgroud) 我使用AVAudioPlayer并将numberofloop设置为-1,因为我想在无限循环中播放音频.起初效果很好,但是在播放音轨的过程中,我连续得到了以下错误日志,我的音轨被停止了.
2017-02-22 10:08:28.863041 TestBridgingHeader [1092:30476] [aqme] 255:AQDefaultDevice(173):跳过输入流0 0 0x0
我正在使用两个媒体播放器来淡出淡出声音.我使用块玩这两个媒体播放器:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{});
Run Code Online (Sandbox Code Playgroud)
为什么我的音轨会停止,为什么会显示AQDefaultDevice错误日志?
我们最近修改了我们的线程机制,支持dispatch_async在大多数地方使用'(在做了很多关于NSOperation和dispatch_async的阅读之后)*.然后我们的代码开始在代码的各个部分与EXC_BAD_ACCESS崩溃,总是在dispatch_async(queue,...)部分,没有明确的模式.通常在20分钟后发生--2小时.
我们的dispatch_async块用于通知听众,如下所示:
NSMutableSet *_listeners; // Initialised elsewhere and filled with interested listeners
void(^block)(id listener); // Block to execute
@synchronized(_listeners) {
for (id listener in _listeners) {
dispatch_async_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // We used different queues for different listeners, but showing only one type of queue here for brevity
dispatch_async(queue, ^{ // CRASHING LINE
block(listener);
});
}
}Run Code Online (Sandbox Code Playgroud)
常见的症状是:
(这是一个自我回答的问题)
*我们喜欢简单dispatch_async,不需要阻止/依赖功能,NSOperationQueue我们很快就会转向C++,所以想保持低水平.
exc-bad-access dispatch grand-central-dispatch ios dispatch-async
我有一组调度工作项,如何等到一项工作完成后再继续队列中的下一项工作?
func AsyncCalls(statusHandler: @escaping (String) -> Void){
var dispatchWorkItems : [DispatchWorkItem] = []
let categoryWorkItem = DispatchWorkItem {
main {
return statusHandler("Loading categories ")
}
self.modelView.getCategories(completion: { data,error in
main {
if data.isEmpty {
return statusHandler("\(error )")
}else{
return statusHandler("Done loading categories")
}
}
})
}
let itemsWorkItem = DispatchWorkItem {
main {
return statusHandler("Loading Inventory ")
}
self.modelView.getInventory(completion: { data,error in
main {
if data.isEmpty {
return statusHandler("\(error )")
}else{
return statusHandler("Done loading Inventory")
}
}
})
}
dispatchWorkItems.append(categoryWorkItem) …Run Code Online (Sandbox Code Playgroud) dispatch grand-central-dispatch dispatch-async swift dispatch-queue
我有一个可以向上滑动的ViewController.单击"保存"时,它会向服务器发送请求.请求完成后,它会关闭ViewController.我将NSURLConnection切换到使用async和blocks(https://github.com/rickerbh/NSURLConnection-Blocks).解除ViewController现在抛出"线程2:程序接收信号:EXC_BAD_ACCESS".如果重要的话,我正在使用ARC.
- (IBAction) savePressed
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://api.com/items/create"]];
//NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[NSURLConnection asyncRequest:request success:^(NSData *data, NSURLResponse *response) {
[self close];
} failure:^(NSData *data, NSError *error) {
[self close];
}];
}
- (void) close
{
[self dismissViewControllerAnimated:YES completion:nil];
}
Run Code Online (Sandbox Code Playgroud)
这是日志
2012-10-24 10:32:43.780 Prayrbox[22268:1703] bool _WebTryThreadLock(bool), 0x1f21fd90: 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 …Run Code Online (Sandbox Code Playgroud) 在非ARC应用程序中,我有一个NSOperation子类,它由一个委托排队,看起来像:
// note that the delegate and element properties are retained
-(id)initWithDelegate:(id<SomeDelegate>)inDelegate element:(SomeElement *)inElement
{
if (self = [super init])
{
[self setDelegate:inDelegate];
[self setElement:inElement];
}
}
-(void)dealloc
{
[_delegate release];
[_element release];
[super dealloc];
}
-(void)main
{
// do stuff
dispatch_async(dispatch_get_main_queue(), ^{
[[self delegate] doSomething:[self element]];
});
}
Run Code Online (Sandbox Code Playgroud)
由于[[self delegate] doSomething:[self element]]将在我的NSOperation对象可能被解除分配后被调用,在将此操作添加到队列之前,是否需要确保在委托中保留"element"?元素对象保留在应用程序的其他位置,但可能会在那里释放.我需要确保当我的代表从NSOperation收回它时,它仍然是一个有效的对象.
只是想知道在dispatch_async中调用它的行为是否会保留传递给它的参数.我当然可以使用NSInvocation和performSelectorOnMainThread来保留它.
我试图延迟不到一秒钟.我从网上找到了这段代码.然而,它不接受不到一秒的延迟.Swift中的Grand Dispatch Concept对我来说有点神秘.我应该如何修改此代码以创建0.3秒的延迟?
let deadlineTime = DispatchTime.now() + .seconds(1) //how to get 0.3 seconds here
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
//code here
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试使恒星“呼吸”在一个循环中。变大然后变小,然后重复。我希望在我的应用程序仍在运行并响应时继续执行此操作。当我在应用程序中转到另一个视图时,我希望动画停止播放。
这就是我得到的
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.async {
self.animateStars()
}
}
func animateStars() {
UIView.animate(withDuration: 4, animations : {
self.star.transform = CGAffineTransform(scaleX: 2.5, y: 2.5)
}) { finished in
NSLog("Star is big. Finished = \(finished)")
}
UIView.animate(withDuration: 4, animations : {
self.star.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
}) { finished in
NSLog("Star is small. Finished = \(finished)")
}
}
Run Code Online (Sandbox Code Playgroud)
这并不困难。而且,我不知道如何在用户单击带有segue的按钮时不让它在后台疯狂运行的情况下使其循环。
我在Objective C中找到了一种解决方案,但是我似乎无法理解如何将其转换为Swift 3.0。此处的示例:https : //stackoverflow.com/a/31978173/5385322
[UIView animateWithDuration:1
delay:0
options:UIViewKeyframeAnimationOptionAutoreverse | UIViewKeyframeAnimationOptionRepeat
animations:^{
yourView.transform = CGAffineTransformMakeScale(1.5, 1.5);
}
completion:nil]; …Run Code Online (Sandbox Code Playgroud) dispatch-async ×11
ios ×8
swift ×5
objective-c ×3
dispatch ×2
asynchronous ×1
crash ×1
ios10 ×1
iphone ×1
nsoperation ×1
retain ×1
swift2 ×1
swift3 ×1
uiimageview ×1
uitableview ×1
xcode ×1