从另一个类的方法中获取NSURLConnection响应(来自辅助类)

时间:2014-04-14 09:40:32

标签: ios objective-c macos nsurlconnection

我有一个类#34; 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代码。

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

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您可以使用块来处理响应。 例如:

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
   }];

}

答案 1 :(得分:0)

更改您的WebAPI类以提供自己的委托接口,或者在异步连接完成时调用请求时使用完成块。