1

我正在尝试为我的 iOS 应用程序组合一个静态类,该类将封装我的 HTTP 通信逻辑。我知道如何通过+符号在 Objective-C 中创建静态方法,但我希望我的类能够接受一个块并在它的任务完成时调用它。到目前为止我得到的类编译得很好,但是当我调用它的函数时,它只会到达某个点并且失败。这是我当前的代码:

#import <UIKit/UIKit.h>

#pragma mark - Globals
#import "Globals.h"

@interface HTTPRequest : NSObject <NSURLConnectionDelegate>
+ (void)GET:(NSMutableURLRequest *)request completionBlock:(void (^)(void))block;
+ (void)POST:(NSMutableURLRequest *)request andBody:(NSString *)requestString completionBlock:(void (^)(void))block;
@end

#import "HTTPRequest.h"

@interface HTTPRequest () {
    NSInteger statusCode;
}
@end

static void (^completionBlock)(void);

@implementation HTTPRequest
+ (void)GET:(NSMutableURLRequest *)request completionBlock:(void (^)(void))block {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

    [request setHTTPMethod:@"GET"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                                  delegate:self];

    if (connection) {
        responseData = [[NSMutableData alloc] init];
    } else {
        NSLog(@"NSURLConnection INSTANCE FAILED");
    };

    completionBlock = block;
}

+ (void)POST:(NSMutableURLRequest *)request andBody:(NSString *)requestString completionBlock:(void (^)(void))block {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

    NSData *requestData = [NSData dataWithBytes:[requestString UTF8String]
                                         length:[requestString length]];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody:requestData];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                                  delegate:self];

    if (connection) {
        responseData = [[NSMutableData alloc] init];
    } else {
        NSLog(@"NSURLConnection INSTANCE FAILED");
    };

    completionBlock = block;
}

#pragma mark - NSURLConnectionDelegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];

    statusCode = [((NSHTTPURLResponse *)response) statusCode];
}

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

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"RESPONSE STRING: %@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

    if (statusCode == 200) {
        completionBlock();
    } else {
        NSLog(@"RESPONSE ERROR: %i", statusCode);
    };
}
@end

我知道 GET 和 POST 函数被调用并且它们创建了NSURLConnection对象。此后,没有任何NSURLConnectionDelegate函数被调用。

任何人都可以发现这个问题,或者,如果我完全错了,请告诉我。提前致谢!

更新

我应该指出,该应用程序是基于 ARC 的。我在这里阅读了有关NSURLConnectionDelegate未调用函数的其他问题,但其中大多数似乎是因为开发人员将对象设置为autorelease. 由于我无法控制它,我假设它不应该是一个问题。

更新 2(重写?)

我做了一些更改,从静态函数中创建了一个类的实例并使用它的实例函数。现在NSURLConnectionDelegate函数被调用了,我知道我的onSuccessBlock块也被调用了,所以整个类一直在执行。坦率地说,我不确定这是否是合法代码,但编译器没有抱怨,我看到了我期待的日志消息,所以我会继续使用它。这是当前的实现:

#import <UIKit/UIKit.h>

@interface HTTPRequest : NSObject <NSURLConnectionDelegate>
+ (void)requestAsGET:(NSMutableURLRequest *)request onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock;
- (void)requestAsGET:(NSMutableURLRequest *)request onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock;
+ (void)requestAsPOST:(NSMutableURLRequest *)request body:(NSString *)body onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock;
- (void)requestAsPOST:(NSMutableURLRequest *)request body:(NSString *)body onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock;
@end

#import "HTTPRequest.h"

@interface HTTPRequest () {
    NSMutableData *responseData;
    NSInteger statusCode;

    void (^onSuccessBlock)(void);
    void (^onFailBlock)(void);
}
@end

@implementation HTTPRequest
- (id)init {
    self = [super init];

    if (self) {
    };

    return self;
}

+ (void)requestAsGET:(NSMutableURLRequest *)request onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock {
    [[[HTTPRequest alloc] init] requestAsGET:request
                                   onSuccess:successBlock
                                      onFail:failBlock];
}

- (void)requestAsGET:(NSMutableURLRequest *)request onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

    [request setHTTPMethod:@"GET"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                                  delegate:self];

    if (connection) {
        onSuccessBlock = successBlock;
        onFailBlock = failBlock;
    } else {
        NSLog(@"NSURLConnection INSTANCE FAILED");
    };
}

+ (void)requestAsPOST:(NSMutableURLRequest *)request body:(NSString *)body onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock {
    [[[HTTPRequest alloc] init] requestAsPOST:request
                                         body:body
                                    onSuccess:successBlock
                                       onFail:failBlock];
}

- (void)requestAsPOST:(NSMutableURLRequest *)request body:(NSString *)body onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

    NSData *requestData = [NSData dataWithBytes:[body UTF8String]
                                         length:[body length]];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody:requestData];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                                  delegate:self];

    if (connection) {
        onSuccessBlock = successBlock;
        onFailBlock = failBlock;
    } else {
        NSLog(@"NSURLConnection INSTANCE FAILED");
    };
}

#pragma mark - NSURLConnectionDelegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];

    statusCode = [((NSHTTPURLResponse *)response) statusCode];
}

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

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"RESPONSE STRING: %@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

    if (statusCode == 200) {
        //  Pass responseData into the block... How?

        onSuccessBlock();
    } else {
        //  Pass statusCode into the block?

        onFailBlock();
    };
}
@end
4

2 回答 2

1

我会使用单例模式而不是静态类。这样您就不必担心另一个请求会覆盖前一个请求的数据。

以您的 NSMutableData responseData为例。您将需要一个实例变量来在连接生命周期中跟踪该数据。我没有看到一个,但如果你有一个,你需要确保没有其他连接可以更新它。这意味着您不能将其设为可能是您最初反应的静态变量。

无论哪种方式,您都应该将responseData变量放入字典中,并以 NSUrlConnection 作为键。这样,在每个委托方法实现中,您都可以从连接中查找数据并执行您需要的任何操作。

因此,在这种情况下,您可以执行以下操作:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                              delegate:self];

if (connection) {
    responseData = [[NSMutableData alloc] init];

    // So this would be a NSMutableDictionary you would store your connection in 
    [requests setValue:responseData forKey:connection];

} else {
    NSLog(@"NSURLConnection INSTANCE FAILED");
};

然后你可以在你的委托方法中做到这一点

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableData *responseData = [requests valueForKey:connection];

[responseData appendData:data];
}

对于我个人的实现,我选择使用CFMutableDictionaryRef而不是 NSMutableDictionary,因为我相信 NSMutableDictionary 不会保留添加到其中的对象。我的代码是在 ARC 之前编写的,因此您可能不必担心。如果您尝试此方法并开始获取 EXC_BAD_ACCESS 或遇到内存问题,请使用 CFMutableDictionaryRef。

希望这能让你朝着正确的方向前进。你的头绝对是在正确的地方:)

基于重写

因此,让我尝试根据您的重写更好地解释我上面提到的内容:

- (void)requestAsGET:(NSMutableURLRequest *)request onSuccess:(void (^)(void))successBlock onFail:(void (^)(void))failBlock {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

    [request setHTTPMethod:@"GET"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
                                                              delegate:self];

    if (connection) {

       /** This is your problem. You are trying to save data to some instance variables
           but there's a data integrity issue here.  If you fire off two requests, the 
           second request will overwrite these two values which would, at the time, contain
           information from the first request */

        onSuccessBlock = successBlock;
        onFailBlock = failBlock;

    } else {
        NSLog(@"NSURLConnection INSTANCE FAILED");
    };
}

所以你在第一步就有一个设计问题,在你解决这个问题之前,从那里发生的事情真的无关紧要。我的建议是使用当前的 NSURLConnection 作为键将您的 ** HTTPRequest** 值对象保存到字典中。这样,在每个委托方法上,您都可以查找特定于该连接的数据并对其进行修改,而不必担心其他请求会影响您的数据。

像这样的东西:

if (connection) {

    // Store the data in an object... call it whatever you want
    SomeObject *someObject = [[SomeObject all] init];
    someObject.responseData = [[NSMutableData alloc] init];
    someObject.onSuccessBlock = successBlock;
    someObject.onFailBlock = failBlock;

    /** Have an NSMutableDictionary that stores all the value objects
        under the corresponding connection since ALL NSURLConnectionDelegate
        methods include a reference to the NSURLConnection for the request */
    [requests setValue:someObject forKey:connection];

} else {
    NSLog(@"NSURLConnection INSTANCE FAILED");
};
于 2012-07-20T06:05:03.660 回答
1

您应该从简单的 NSURLConnection 包装器(例如https://github.com/nst/STHTTPRequest )中获得灵感。

此外,您可以在 ARC 项目中使用非 ARC 代码。为此,您可以告诉编译器不要基于文件使用 ARC Disable Automatic Reference Counting for Some Files

于 2012-07-20T09:25:47.153 回答