NSURLConnection delegate methods not executing

白昼怎懂夜的黑 提交于 2019-12-23 18:40:15

问题


I'm running the following example code from Apple -

        NSString *requestURL = [[NSString alloc] initWithString:@"http://google.com/"];         
        NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:requestURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
        NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

        if(theConnection) {

            NSLog(@"The connection has started...");

        } else {

            NSLog(@"Connection has failed...");

        }

But the delegate methods below aren't being called. Can anyone please help me out?

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

回答1:


If you are performing this on a background thread, the thread is probably exiting before the delegates can be called. Look at calling in your method that starts the transfer just after you call the method that fires off the background thread, CFRunLoopRun(). Then in your callbacks connectionDidFinishLoading: and connection:didFailWithError: make sure you also run:

CFRunLoopStop(CFRunLoopGetCurrent());

At the end of those methods, otherwise you will never return.




回答2:


Are you setting the delegate? In the class interface where that code is located, add <NSURLConnectionDelegate>

For example:

@interface myClass : parentClass<NSURLConnectionDelegate>

Good luck!



来源:https://stackoverflow.com/questions/3421054/nsurlconnection-delegate-methods-not-executing

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