NSURLConnection数据检索

时间:2013-09-22 19:09:30

标签: ios objective-c nsurlconnection httprequest

我对NSURLConnection有一个非常令人费解的问题。它在另一个线程或其他东西中返回数据,事情没有按正确的顺序工作。我应该接收json数据然后解析它,但是在解析器失败后实际上正在接收数据。这是日志。

  

2013-09-22 14:44:40.454 WebServiceExample [39306:a0b]解析错误:错误Domain = NSCocoaErrorDomain Code = 3840“操作无法完成。(Cocoa error 3840.)”(无值。) UserInfo = 0xa0b47e0 {NSDebugDescription =无值。}   2013-09-22 14:44:41.312 WebServiceExample [39306:a0b]成功!收到112字节的数据

我正在制作一个小框架来缓解我的生活以连接到rails API,我称之为客观轨道OR,但我已经花了整个周末试图弄清楚我做错了什么。这是代码:

@interface ORObject : NSObject

@property (nonatomic, retain) NSMutableDictionary *properties;
@property (nonatomic, retain) ORWebManager *webManager;
@property (nonatomic, retain) NSString *route;
@property (nonatomic, retain) NSString *singularClassName;

- (id) initWithRoute:(NSString *) route webManager:(ORWebManager *) webManager;
- (id) initWithRoute:(NSString *) route;
- (ORObject *) find:(NSInteger) identifier;
@end

以下是find的实现:

- (ORObject *) find:(NSInteger) identifier
{

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/%ld.%@", [    ORConfig sharedInstance].baseURL, self.route, (long)identifier, self.webManager.    parser.contentType]];

    ORObject *object = [self.webManager httpGet:url];

    if (object) {
        object.route = self.route;
        object.webManager = self.webManager;
    }

    return object;
}

这是ORWebManager类的httpGet方法

- (ORObject *) httpGet:(NSURL *)url
{
    ORGetRequester *requester = [[ORGetRequester alloc] init];
    NSMutableData *data = [requester request:url];
    return [self.parser toObject:data];
}

ORGetRequester的超类是ORHTTPRequester,它实现了NSURLConnectionDelegate协议方法

@interface ORHTTPRequester : NSObject<NSURLConnectionDelegate>
@property (nonatomic, retain) NSMutableData *receivedData;
@property (nonatomic, retain) NSMutableURLRequest *req;
@property (nonatomic, retain) NSURLConnection *connection;
@end

@implementation ORHTTPRequester
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse
    [self.receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeeded! Received %d bytes of data",[self.receivedData length]);
}   
@end

最后这里是ORGetRequester,这就是“神奇”发生的地方。

@interface ORGetRequester : ORHTTPRequester
- (NSMutableData *) request:(NSURL *)url;
@end

@implementation ORGetRequester
- (NSMutableData *) request:(NSURL *)url
{
    self.req = [NSMutableURLRequest requestWithURL:url
                                              cachePolicy:NSURLRequestUseProtocolCachePol    icy
                                          timeoutInterval:60.0];
    self.receivedData = [[NSMutableData alloc] init];
    self.connection = [[NSURLConnection alloc] initWithRequest:self.req delegate:self];

    if (!self.connection) {
        NSLog(@"Connection Failed");
    }

    return self.receivedData;
}
@end

1 个答案:

答案 0 :(得分:1)

self.connection = [[NSURLConnection alloc] initWithRequest:self.req delegate:self];

立即返回,因为它启动了异步操作。您需要在调用connectionDidFinishLoading:时解析数据。

或考虑使用:

+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler

http操作完成后将调用完成块。处理完成块中的数据并通知任何需要该数据的对象。如果您不需要其他委托方法,这可能是一个不错的选择。