我正在尝试为我的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(REWRITE?)
我在静态函数中做了一些更改,我创建了一个类的实例并使用它的实例函数。现在调用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
答案 0 :(得分:1)
我会使用Singleton Pattern而不是静态类。然后,您将不必担心另一个请求覆盖前一个请求的数据。
以您的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。
希望这能让你朝着正确的方向前进。你的头脑肯定是在正确的地方:)
基于REWRITE
因此,让我尝试根据您的重写更好地解释我上面提到的内容:
- (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");
};
答案 1 :(得分:1)
您应该从简单的NSURLConnection包装器中获取灵感,例如https://github.com/nst/STHTTPRequest。
此外,您可以在ARC项目中使用非ARC代码。为此,您可以告诉编译器不要在文件基础上使用ARC Disable Automatic Reference Counting for Some Files。