我正在尝试开发一个应该执行以下操作的简单OS X应用程序:
此应用程序应该在没有GUI的情况下工作,因此我使用Xcode命令行工具。该应用程序组织如下:
我的问题是,如果我运行应用程序,它不会连接到登录服务,因为它不会调用NSConnectionDelegate方法。我在网上搜索,我发现连接应该在主线程中,我使用以下代码测试它:NSLog(@"Is%@ main thread", ([NSThread isMainThread] ? @"YES" : @" NOT"));
并且它返回我,连接在主线程中,所以我没有&#39 ;不知道它为什么不运行NSConnectionDelegate方法。如果您需要,我可以发布我的Connection.m类的代码,以了解它为什么不能正常工作。我希望你能帮助我解决这个问题。
Connection.m
#import "Connection.h"
#import "CheckNews.h"
@interface Connection() {
NSMutableData *responseData;
}
@property(nonatomic,strong)NSString *fakeBundleIdentifier;
@property BOOL installNSBundleHook;
@end
@implementation Connection
- (id)initWithFakeBundle:(NSString *)fakeBundleIdentifier andInstallNSbundleHook:(BOOL)installNSBundleHook {
if (self) {
self.fakeBundleIdentifier = fakeBundleIdentifier;
self.installNSBundleHook = installNSBundleHook;
}
return self;
}
- (id)sendRequestToURL:(NSString *)urlString withMethod:(NSString *)method withUsername:(NSString *)username withPassword:(NSString *)password andSerialNumber:(NSString *)serialNumber {
NSURL *finalURL;
if ([method isEqualToString:@"POST"]) {
finalURL = [NSURL URLWithString:urlString];
} else {
NSLog(@"Metodo no previsto");
}
NSString *post = [NSString stringWithFormat:@"username=%@&password=%@&serialNumber=%@", username, password, serialNumber];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)postData.length];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:finalURL];
[request setHTTPMethod:method];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
[connection start];
}
return connection;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%@", error);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSDictionary *json;
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
if ([self loginWithSuccessFromJson:json]) {
[self checkNews];
}
}
- (BOOL)loginWithSuccessFromJson:(NSDictionary *)json {
int success = [[json objectForKey:@"success"]intValue];
if (success == 1) {
return YES;
} else {
return NO;
}
}
- (void) checkNews {
CheckNews *checkNews = [[CheckNews alloc]initWithFakeBundle:self.fakeBundleIdentifier andInstallNSbundleHook:self.installNSBundleHook];
for(;;) {
[checkNews sendRequestToURL:@"" withMethod:@"GET"];
}
}