7

我在一些看起来相当
简单但我似乎无法开始工作的事情上度过了一段时光。我正在构建一个
从网络主机检索数据的 iPhone 应用程序。我正在尝试
与主机建立异步连接,因为我想
在连接期间保持设备空闲。(sendSynchronousRequest 冻结
电话,直到请求完成。)这是我的连接代码:

//temp url to see if data is returned:
NSURL *theURL = [NSURL URLWithString:@"http://www.theappleblog.com/feed"];

NSURLRequest *dataRequest = [NSURLRequest requestWithURL:theURL
             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
             timeoutInterval:60];

/* establish the connection */  
theConnection = [[NSURLConnection alloc]
                 initWithRequest:dataRequest
                        delegate:self
                startImmediately:YES];

if (theConnection == nil) { 
    NSLog(@"Connection Failure!");
    self.urlData = nil; 
} else {
    self.urlData = [[NSMutableData data] retain];   
}

我已经设置了所有适当的委托方法:

-(void)connection:(NSURLConnection *)connection
       didReceiveResponse:(NSURLResponse*)response
{
    [urlData setLength:0];
    UIApplication *application = [UIApplication sharedApplication];
    application.networkActivityIndicatorVisible = YES;
    NSLog(@"Received Response!");
}

-(void)connection:(NSURLConnection *)connection
       didReceiveData:(NSData*)incrementalData
{
    [self.urlData appendData:incrementalData];

    NSNumber *resourceLength = [NSNumber
              numberWithUnsignedInteger:[self.urlData length]];
    NSLog(@"resourceData length: %d", [resourceLength intValue]);
    NSLog(@"filesize: %d", self.urlDataSize);
    NSLog(@"float filesize: %f", [self.urlDataSize floatValue]);
}

-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
    NSLog(@"Connection finished loading\n");
    NSLog(@"Succeeded! Received %d bytes of data",[urlData length]);
    _isFinished = YES;
    UIApplication *application = [UIApplication sharedApplication];
    application.networkActivityIndicatorVisible = NO;
}

- (void)connection:(NSURLConnection *)connection
        didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@",[error localizedDescription]);
}

As you can see, I've got a boat-load of log messages because I wanted
to see if anything was coming through at all. My connection test
comes back as TRUE but no data ever gets loaded. Like I said, I'm sure
I must be doing (or not doing) something really stupid. But what?
Any help would be most appreciated.

Thanks, Lawrence

4

9 回答 9

2

The problem was that I was continuing program flow and not stopping to allow the connection to finish downloading. Thank you for all of the suggestions.

于 2009-06-16T22:28:16.257 回答
1

A few suggestions:

  • In your first snippet, instead of theConnection try assigning to self.theConnection to make sure the property accessor methods are called. In various places you also interchange self.urlData and urlData. Might want to make them all consistent by going through self.

  • You may want to make the dataRequest a property as well and go through self to make sure it gets retained.

  • self.urlData = [[NSMutableData data] retain]; -- you shouldn't need that extra retain. Going through self does it for you. The extra retain will make it so the object will stick around and leak even when all is done.

  • On a related note, in your NSLogs make sure you print out the retain count for each object. Also, you may want to have a general clean-up routine around to release these structures (or sets self.foo = nil) so at any point if it barfs out you can call the routine to get things cleaned up.

  • Get a copy of Charles or WireShark (or run tcpdump in the console) and watch the network traffic. It'll help pinpoint at what stage in the flow it's failing.

于 2009-05-13T06:18:19.640 回答
0

Initial thought - is the object that has all this code being retained properly? It could be it's being released, and thus deallocating the connection...

Otherwise you should at least see the response.

于 2009-04-26T20:23:06.050 回答
0

Nothing obviously wrong up there. I have code that's substantially the same and works fine. The only differences I see are:

  • I use NSURLRequestUseProtocolCachePolicy instead of NSURLRequestReloadIgnoringLocalCacheData

  • I use connection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; instead of specifying startImmediately: YES (since it's the default)

It would be helpful to know which, if any, of your delegate methods are getting called. At the very least, you ought to get at least one or the other of connectionDidFinishLoading or connectionDidFail being called. If not, then something's probably wrong with your delegate setup - are you ABSOLUTELY sure that the delegate method signatures are correct, and that you're passing in the right item as the delegate?

于 2009-04-26T21:33:05.833 回答
0

It's hard to zero in on anything since it's not clear from your question which, if any of the NSLog statements executes. Please be a little more clear about the results you're getting.

From a quick look the only thing that looks like a potential problem is that you have a race condition when you set up the connection. If the network is especially fast there's a slim but nonzero chance that -connection: didReceiveData: will be called before self.urlData has been allocated. I'd suggest allocating urlData either before initiating the connection or in -connection:didReceiveResponse: to prevent this.

If that doesn't fix it, more information from you is needed.

于 2009-04-26T21:58:35.617 回答
0

This doesn't answer your question directly, but you might consider looking into Ben Copsey's ASIHTTPRequest library, which wraps around CFNetwork classes and includes asynchronous, threaded request code that takes a lot of work out of doing this properly.

于 2009-04-27T00:04:40.400 回答
0

You say this code works fine using the asynchronous method? Testing that URL, it redirects to another, so what if you implement the redirection delegate methods? What if you try some different URLs?

于 2009-04-27T09:04:07.360 回答
0

Is the app otherwise responsive? Is the runloop running? What does the app do after starting the request -- does it return from its event handler back to the runloop? (If not, you'll never get any of your callbacks, because they're delivered via the runloop.)

于 2009-05-01T00:27:03.043 回答
0

NSURLConnection is designed to work with any type of protocol, not just HTTP. This means that connection:didFail:withError is called for connection errors, but not for protocol errors. You're not checking for protocol errors -- you have to catch them in connection:didReceiveResponse:. The trick is that the response object that is passed in is actually a NSHTTPURLResponse object. If you check the response's statusCode, I'll bet you're getting an HTTP error such as 404 or server 500.

于 2009-05-13T02:38:17.530 回答