在我的IOS应用程序中,我有一个登录方法,用于向java服务器发送用户名和密码。 问题是,如果服务器处于脱机状态,应用程序将冻结。当服务器重新启动时,应用程序将继续运行。 那么是否有一个异常处理,我应该为应用程序在发送数据之前检查服务器是否在线?
- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"XXXXX", 678, &readStream,
&writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
}
-(void) connection{
[self initNetworkCommunication];
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
////// thats how I'm sending the username and password
NSString *username= [NSString stringWithFormat:@"%@\n",UsernameTextField.text];
NSString *password=[NSString stringWithFormat:@"%@\n",PasswordTextField.text];
NSLog(@"%@ %@",username,password);
NSData *usernamedata = [[NSData alloc] initWithData:[username dataUsingEncoding:NSASCIIStringEncoding]];
NSData *passworddata = [[NSData alloc] initWithData:[password dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[usernamedata bytes] maxLength:[usernamedata length]];
[outputStream write:[passworddata bytes] maxLength:[passworddata length]];
答案 0 :(得分:1)
我还建议你看看AFNetworking
。它解决了网络的所有问题,包括使用块的异步连接。
我假设您的应用程序冻结,因为您的网络连接在与UI相同的线程上运行,并且线程正在等待连接超时。
我建议你看看AFNetworking的例子。这是使用AFNetworking
:
if ([AFNetworkReachabilityManager sharedManager].reachable)
{
...
}