ios – 在另一个类的方法内获取NSURLConnection响应(来自辅助类)

我有一个类“WebAPI”,它处理所有Web API调用,该类通过其基于异步委托的调用使用NSURLConnection.

每当一个对象需要与Web API通信时,它将使用一个WebAPI实例并在登录的情况下调用所需的方法,如下所示,我从AppDelegate进行以下调用:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
     WebAPI *webAPI = [[WebAPI alloc] init];
     [webAPI performLoginWithUserName:@"test1@myserver.com" andPassword:@"password"];
}

问题是,一旦执行了performLoginWithUserName:andPassword调用,代码就会继续进行,并且在WebAPI.m中实现的委托方法中会收到任何/所有响应.

这是一个真正的问题,因为我需要能够获取响应代码以及在类方法中接收到的来自WebAPI调用的所有数据.我希望能够:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
     WebAPI *webAPI = [[WebAPI alloc] init];
     WebAPIResponse * webAPIRespnse = [webAPI performLoginWithUserName:@"test1@myserver.com" andPassword:@"password"];
}

其中WebAPIResponse类是一个自定义类,它将包含HTTP状态代码和接收的任何数据.

如果我将WebAPI.m更改为使用NSURLConnection sendSynchronousRequest,这是可以实现的,但这并不能使我接收所有HTTP代码.

什么是满足这一要求的最佳方式?

谢谢您的帮助.

最佳答案 您可以使用块来处理响应.

例如:

WebApi.h
- (void)performLoginWithUsername:(NSString *)userName 
                     andPassword:(NSString *)password
                    successBlock:(void(^)(NSData *response))successBlock
                    failureBlock:(void(^)(NSError *error))failureBlock;

WebApi.m
@interface WebAPI()
    @property (nonatomic, copy) void(^authorizationSuccessBlock)(NSData *response);
    @property (nonatomic, copy) void(^authorizationFailureBlock)(NSError *error);
@end

@implementation WebAPI
- (void)performLoginWithUsername:(NSString *)userName 
                     andPassword:(NSString *)password
                    successBlock:(void(^)(NSData *response))successBlock
                    failureBlock:(void(^)(NSError *error))failureBlock {
    self.authorizationSuccessBlock = successBlock;
    self.authorizationFailureBlock = failureBlock;
    // NSURLConnection call for authorization here
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if (self.authorizationSuccessBlock != nil) {
        self.authorizationSuccessBlock(data);
        self.authorizationSuccessBlock = nil;
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    if (self.authorizationFailureBlock != nil) {
        self.authorizationFailureBlock(error);
        self.authorizationFailureBlock = nil;
    }
}

AppDelegate.m
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
   WebAPI *webAPI = [[WebAPI alloc] init];
   [webAPI performLoginWithUserName:@"test1@myserver.com" andPassword:@"password" successBlock:^(NSData *response) {
      // Handle result here
   } failureBlock:^(NSError *error) {
      // Handle error here
   }];

}

点赞