Cancel NSData initWithContentsOfURL in NSOperation

为君一笑 提交于 2019-12-11 13:27:26

问题


I currently have the following code in an NSOperation that has an observer for keyPath "isCancelled":

    downloaded = FALSE;
    NSURL *url = [NSURL URLWithString:requestString];
    dataXML = [[NSData alloc] initWithContentsOfURL:url];
    downloaded = TRUE;

I want to make it so that the observeValueForKeyPath function is able to cancel the dataXML continuing or just completely stop the NSOperation once the NSOperation is sent a cancel message. The NSOperation's cancelling operation cancel only notifies the operation that it should stop, but will not force my operation's code to stop.


回答1:


You can't cancel it.

If you want to be able to cancel the load mid-way through, use NSURLConnection operating in asynchronous mode. It's a bit more work to set up but you can cancel at any point in the download process.

Alternatively, you could use this handy class I wrote that wraps an async NSURLConnection and its delegate in a single method call ;-)

NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[RequestQueue mainQueue] addRequest:request completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    if (data && error == nil)
    {
        //do something with your downloaded data
    }
}];

//to cancel the download at any time, just say
[[RequestQueue mainQueue] cancelRequest:request];

Easy!

</shamelessSelfPromotion>

Note that the request above is already asynchronous, and the class already manages queuing of multiple requests, so you don't need to (and shouldn't) wrap it in an NSOperationQueue.



来源:https://stackoverflow.com/questions/9117332/cancel-nsdata-initwithcontentsofurl-in-nsoperation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!