2014-04-11 161 views
0

在我的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]]; 

回答

1

我也建議你看看AFNetworking。它解決了所有與網絡有關的問題,包括使用塊的異步連接。

我假設您的應用程序凍結,因爲您的網絡連接與UI所在的同一線程上運行,並且線程正在等待連接超時。

我建議你看看AFNetworking的例子。這是AFNetworking需要的可達性代碼:

if ([AFNetworkReachabilityManager sharedManager].reachable) 
{ 
    ... 
} 
相關問題