NSURLConnection不会返回dataWithContentsOfURL所做的数据

时间:2013-02-11 16:29:46

标签: iphone json nsurlconnection nsdata

我有一个应用程序,我曾经用dataWithContentsOfURL获取我的json数据 但是因为我需要把它变成异步时尚 现在我使用NSURLConnection来处理这个问题我没有收到任何有用的数据,我得到的是didReceiveResponse方法中的状态码200,但永远不会调用didReceiveData。 在connectionDidFinishDownloading destinationURL返回null

我不知道wat会遇到这个问题,我真的很感激一些帮助。

代表

#import "NetWorkToGuiDelegate.h"

@implementation NetWorkToGuiDelegate
@synthesize data;
@synthesize caller;

- (id) init: (SEL) pointer :(NSObject *) c;
{
    doWhenDone = pointer;
    self.caller = c;
    data = [[NSMutableData alloc]init];
    return self;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];

    NSLog(@"%@",responseText);

}

- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
{
    NSLog(@"post download finished");
    data = [NSData dataWithContentsOfURL:destinationURL];
    NSLog(@"data: %@",data);
    NSLog(@"URLconnection %@", connection.currentRequest);

    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    [caller performSelector:doWhenDone withObject:data];
    #pragma clang diagnostic pop
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [self.data setLength:0];
    NSHTTPURLResponse *resp= (NSHTTPURLResponsae *) response;
    NSLog(@"got responce with status %d",[resp statusCode]);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d
{
    NSLog(@"data recieved %@",d);
    [self.data appendData:d];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", @"")
                                message:[error localizedDescription]
                               delegate:nil
                      cancelButtonTitle:NSLocalizedString(@"OK", @"")
                      otherButtonTitles:nil] show];
    NSLog(@"failed");
}

// Handle basic authentication challenge if needed
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSString *username = @"username";
    NSString *password = @"password";

    NSURLCredential *credential = [NSURLCredential credentialWithUser:username
                                                             password:password
                                                          persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}

@end

电话

NetWorkToGuiDelegate *nwgd = [[NetWorkToGuiDelegate alloc] init:@selector(login:) :self];
    NSString *stringURL = [NSString stringWithFormat:@"%@%@%@%@", dk.baseURL, @"menu?code=",dk.loginCode,@"&v=1"];
    NSURL *url = [NSURL URLWithString:stringURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:nwgd];
    [urlConnection start];

我只想补充一下,调用发生在主线程上

1 个答案:

答案 0 :(得分:0)

实际上有很多要点可以回答这个问题,并且有很多questions on SO本身

完成这个不错的post

必须从苹果本身阅读doc。(包含代码示例和解释)

希望这能为您解决问题。

修改

-(void)startAConnection
{
    // Create the request.
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    // create the connection with the request
    // and start loading the data
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        receivedData = [NSMutableData data];
    } else {
        // Inform the user that the connection failed.
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.

    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.

    // receivedData is an instance variable declared elsewhere.
    [receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);

}

调用startAConnection以启动进程

注意:不要忘记.h

中的<NSURLConnectionDelegate>

快乐编码:)