2011-06-16 91 views
1

我有一個應用程序,我登錄表格中的用戶名和密碼textfields。當用戶輸入他/她的用戶名和密碼,然後點擊提交按鈕,它會去服務器API數據庫,並檢查用戶是否有效。如果連接不是它們的值在sqlite數據庫檢查.if在sqlite數據庫if用戶的用戶名和密碼進行驗證,然後允許用戶進入應用程序,否則他將不得不註冊。我嘗試了下面的代碼,但現在我很困惑在哪裏應該把我的代碼。 我已檢查服務器連接和sqlite連接。我的答案是,如果用戶一次又一次地登錄,那麼用戶名和密碼應該總是先檢查服務器而不是在sqlite數據庫中。如果服務器關閉,則用戶名和密碼應該從sqlite數據庫檢查。 這是我的代碼:如何檢查網絡連接是否可用在iphone

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil]; 

    internetReachable = [[Reachability reachabilityForInternetConnection] retain]; 
    [internetReachable startNotifier]; 

    // check if a pathway to a random host exists 
    hostReachable = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain]; 
    [hostReachable startNotifier]; 

The callback is as follows; 
- (void) checkNetworkStatus:(NSNotification *)notice 
{ 
    // called after network status changes 

    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus]; 
    switch (internetStatus) 

    { 
        case NotReachable: 
        { 
            break; 

        } 
        case ReachableViaWiFi: 
        { 
            break; 

        } 
        case ReachableViaWWAN: 
        { 
            break; 

        } 
    } 

    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus]; 
    switch (hostStatus) 

    { 
        case NotReachable: 
        { 
            break; 

        } 
        case ReachableViaWiFi: 
        { 
            break; 

        } 
        case ReachableViaWWAN: 
        { 
            break; 

        } 
    } 
} 


this is my api controller.m where i am fetching values from my api server and inserting values in sqlite database 


// 
// apicontroller.m 
// apitest 
// 
// Created by raji.nair on 6/10/11. 
// Copyright 2011 __MyCompanyName__. All rights reserved. 
// 

#import "apicontroller.h" 
#import "Result.h" 
#import "global.h" 

#import <sqlite3.h> 
#define DATABASE_NAME @"journey.sqlite" 
#define DATABASE_TITLE @"journey" 



@implementation apicontroller 
@synthesize txtUserName; 
@synthesize txtPassword; 
@synthesize txtfirstName; 
@synthesize txtlast; 
@synthesize txtEmail; 
@synthesize webData;  

- (NSString *) getWritableDBPath { 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
    NSString *documentsDir = [paths objectAtIndex:0]; 
    return [documentsDir stringByAppendingPathComponent:DATABASE_NAME]; 
} 

-(void)createEditableCopyOfDatabaseIfNeeded 
{ 
    // Testing for existence 
    BOOL success; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                 NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DATABASE_NAME]; 
    NSLog(@"%@",writableDBPath); 

    success = [fileManager fileExistsAtPath:writableDBPath]; 
    if (success) 
     return; 

    // The writable database does not exist, so copy the default to 
    // the appropriate location. 
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] 
           stringByAppendingPathComponent:DATABASE_NAME]; 
    success = [fileManager copyItemAtPath:defaultDBPath 
            toPath:writableDBPath 
            error:&error]; 
    if(!success) 
    { 
     NSAssert1(0,@"Failed to create writable database file with Message : '%@'.", 
        [error localizedDescription]); 
    } 
} 

-(void)sendRequest 
{ 
    UIDevice *device = [UIDevice currentDevice]; 
    NSString *udid = [device uniqueIdentifier]; 
    NSString *sysname = [device systemName]; 
    NSString *sysver = [device systemVersion]; 
    NSString *model = [device model]; 
    NSLog(@"idis:%@",[device uniqueIdentifier]); 
    NSLog(@"system nameis :%@",[device systemName]); 
    NSLog(@"System version is:%@",[device systemVersion]); 
    NSLog(@"System model is:%@",[device model]); 
    NSLog(@"device orientation is:%d",[device orientation]); 
    NSString *post = [NSString stringWithFormat:@"Loginkey=%@&Password=%@&DeviceCode=%@&Firmware=%@&IMEI=%@",txtUserName.text,txtPassword.text,model,sysver,udid]; 
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 
    NSLog(@"%@",postLength); 
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; 
    [request setURL:[NSURL URLWithString:@"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login"]]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:postData]; 

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

    if (theConnection) { 
     webData = [[NSMutableData data] retain]; 
     NSLog(@"%@",webData); 
    } 
    else 
    { 

    } 

} 

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    [webData setLength: 0]; 
} 

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

} 

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{  
    [connection release]; 
    [webData release]; 

} 

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{  
    NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@",loginStatus); 

    NSString *json_string = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding]; 

    NSDictionary *result = [json_string JSONValue]; 
    NSArray *values = [result objectForKey:@"Result"]; 
    NSMutableArray *results = [[NSMutableArray alloc] init]; 

    for (int index = 0; index<[values count]; index++) { 
     NSMutableDictionary * value = [values objectAtIndex:index]; 
     Result * result = [[Result alloc] init]; 
     result.UserID = [value objectForKey:@"UserId"]; 
     result.FirstName = [value objectForKey:@"FirstName"]; 
     result.LastName =[value objectForKey:@"LastName"]; 
     result.Email =[value objectForKey:@"Email"]; 
     result.ProfileImage =[value objectForKey:@"ProfileImage"]; 
     result.ThumbnailImage =[value objectForKey:@"ThumbnailImage"]; 
     result.DeviceInfoId =[value objectForKey:@"DeviceInfoId"]; 
     NSLog(@"%@",result.UserID); 


     [results addObject:result]; 
     [result release]; 
    } 



    for (int index = 0; index<[results count]; index++) { 
     Result * result = [results objectAtIndex:index]; 
     //save the object variables to database here 


     [self createEditableCopyOfDatabaseIfNeeded]; 

     NSString *filePath = [self getWritableDBPath]; 

     sqlite3 *database; 

     if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) { 
      NSDate *dt = [NSDate date]; //get current date 
      NSString *timestamp = [dt description]; 
      NSString *journeyid = [NSString stringWithFormat:@"%@_%@_%@", result.UserID, result.DeviceInfoId, timestamp]; 

      const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,FirstName,Email,JourneyID) VALUES (?,?,?,?,?)"; 
      sqlite3_stmt *compiledStatement; 
      if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { 
       sqlite3_bind_text(compiledStatement, 1, [result.UserID UTF8String],-1,SQLITE_TRANSIENT); 
       sqlite3_bind_text(compiledStatement, 2, [result.DeviceInfoId UTF8String],-1,SQLITE_TRANSIENT); 
       sqlite3_bind_text (compiledStatement, 3, [result.FirstName UTF8String],-1,SQLITE_TRANSIENT); 
       sqlite3_bind_text (compiledStatement, 4, [result.Email UTF8String],-1,SQLITE_TRANSIENT); 
       sqlite3_bind_text(compiledStatement, 5, [journeyid UTF8String], -1, SQLITE_TRANSIENT); 

      } 
      if(sqlite3_step(compiledStatement) != SQLITE_DONE) { 
       NSLog(@"Save Error: %s", sqlite3_errmsg(database)); 
      } 
      else { 
       UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"Record added" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
       [alert show]; 
       [alert release]; 
       alert = nil; 
      } 

      sqlite3_finalize(compiledStatement); 
     } 
     sqlite3_close(database); 
    } 

    [loginStatus release];   
    [connection release]; 
    [webData release]; 
} 

-(IBAction)click:(id)sender 
{ 
    [self sendRequest]; 
} 
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
    [txtfirstName resignFirstResponder]; 
    [txtlast resignFirstResponder]; 
    [txtUserName resignFirstResponder]; 
    [txtPassword resignFirstResponder]; 
    [txtEmail resignFirstResponder]; 
} 
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 
- (void)viewDidLoad { 


    [super viewDidLoad]; 
    //[self sendRequest]; 
} 

- (void)didReceiveMemoryWarning { 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 

    // Release any cached data, images, etc. that aren't in use. 
} 

- (void)viewDidUnload { 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 


- (void)dealloc { 
    [super dealloc]; 
} 


@end 


this is class where i am creating nsstring variables of my json object 

// 
// Result.h 
// apitest 
// 
// Created by pradeep.yadav on 6/14/11. 
// Copyright 2011 __MyCompanyName__. All rights reserved. 
// 

#import <Foundation/Foundation.h> 


//TokenID":"Vao13gifem","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"[email protected]","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"12"}],"ErrorCode":900} 
//Terminating in response to SpringBoard's termination. 



@interface Result : NSObject { 

    NSString * UserID; 
    NSString *FirstName; 
    NSString *LastName; 
    NSString *Email; 
    NSString *ProfileImage; 
    NSString *ThumbnailImage; 
    NSString *DeviceInfoId; 
} 
@property (nonatomic,retain) NSString *UserID; 
@property (nonatomic,retain) NSString *FirstName; 
@property (nonatomic,retain) NSString *LastName; 
@property (nonatomic,retain) NSString *Email; 
@property (nonatomic,retain) NSString *ProfileImage; 
@property (nonatomic,retain) NSString *ThumbnailImage; 
@property (nonatomic,retain) NSString *DeviceInfoId; 

@end 



// 
// Result.m 
// apitest 
// 
// Created by pradeep.yadav on 6/14/11. 
// Copyright 2011 __MyCompanyName__. All rights reserved. 
// 

#import "Result.h" 


@implementation Result 
@synthesize UserID; 
@synthesize FirstName; 
@synthesize LastName; 
@synthesize Email; 
@synthesize ProfileImage; 
@synthesize ThumbnailImage; 
@synthesize DeviceInfoId; 





- (void)dealloc { 
    [super dealloc]; 
    [UserID release]; 
    [FirstName release]; 
    [LastName release]; 
    [Email release]; 
    [ProfileImage release]; 
    [ThumbnailImage release]; 
    [DeviceInfoId release]; 
} 


@end 


Please help me in solving this problem that if my server api that is available through netconnection is not available then my username and password values should be fetched and validated from database.Thanks 

回答

2
NSMutableURLRequest * serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl]; 
[serviceRequest setValue:@"text/xml" forHTTPHeaderField:@"Content-type"]; 
[serviceRequest setHTTPMethod:@"POST"]; 
[serviceRequest setHTTPBody:[xmlString dataUsingEncoding:NSUTF8StringEncoding]]; 
NSData *responseData; 
NSURLResponse * serviceResponse; 
NSError * serviceError; 
responseData = [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError]; 
NSString *resp=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
NSLog(@"RETRIEVING:%@",resp); 

if(responseData != NULL) 
{ 
//connection exist 
} 
else 
{ 
//Connection doesn't exist 
} 
+0

嗨@rptwshi,當responseData = NULL應該是什麼done.Can你給我出個主意! – Rani 2011-06-17 04:56:56

-1

我查閱了你的問題。我認爲你應該遵循以下流程:

1)用戶將在登錄表單中輸入「用戶名」和「密碼」。

2)然後先檢查本地數據庫。

3)如果用戶存在,則用戶可以直接登錄並訪問應用程序。

4)如果用戶不存在,則從實時服務器檢查它的憑證。 5)如果用戶有效,則輸入用戶名&密碼到本地數據庫。所以,下次他可以直接登錄。

6)如果用戶無效,那麼只需提供拒絕訪問的消息。

現在,檢查網絡連接: 爲此,採取一個網絡視圖(網絡視圖將是不可見的)。然後打開像「http://www.google.com」這樣的簡單網站,並實施網絡查看委託方式。

在web的視圖委託方法:

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{ 

    [self connectionFailed:error]; 
} 
下面

是 「爲connectionFailed」 功能:

-(void)connectionFailed:(NSError *)error{ 

if ([error code] == -999) { 
    //show error alert, etc. 
    //NSLog(@"-999 Detected, Do Nothing"); 
    //NSLog([error localizedDescription]); 
} 
else if([error code] == -1009 || [[error localizedDescription] isEqualToString:@"no Internet connection"]){ 
    [self hideLoading]; 
    [connectionView loadHTMLString:@"<body bgcolor=#58637C><br><br><br><br><font size=5 color=white>Please turn on your Internet connection to access this application.</font></body>" baseURL:nil]; 
    [connectionView setFrame:CGRectMake(0.0, 0.0, 320.0, 431.0)]; 
    [self.view addSubview:connectionView]; 
} 
else if([error code] == -1001 || [[error localizedDescription] isEqualToString:@"timed out"]){ 
    [self hideLoading]; 
    [connectionView loadHTMLString:@"<body bgcolor=#58637C><br><br><br><br><font size=5 color=white>Request Timed Out.</font></body>" baseURL:nil]; 
    [connectionView setFrame:CGRectMake(0.0, 0.0, 320.0, 431.0)]; 
    [self.view addSubview:connectionView]; 
} 
else if (error != NULL) { 
    [self hideLoading]; 
    [connectionView loadHTMLString:@"<body bgcolor=#58637C><br><br><br><br><font size=5 color=white>Error loading page, Please try again later.</font></body>" baseURL:nil]; 
    [connectionView setFrame:CGRectMake(0.0, 0.0, 320.0, 431.0)]; 
    [self.view addSubview:connectionView]; 
} 
else{  
} 
} 

這裏,connectionView視圖是另一個網絡圖。您可以簡單地用UIAlerView用適當的消息替換代碼。

希望它會適合你。

如有任何困難,請通知我。

0

這裏的展示已晚,但檢查此問題的最佳解決方案是使用可達性。可達性由蘋果公司編寫爲「示例代碼」,但是迄今爲止,完美處理網絡狀態的最完整方式。檢查出Reachability Guide

下面是關於如何使用可達的一些信息:Reachability Guide for iOS 4