2016-05-04 2 views
0

Я работаю над приложением, использующим локальную базу данных как sqlite.Как создать собственный файл sqlite в ios?

Где я хочу создать пользовательский файл для sqlite Я не знаю, как это сделать.

Любая помощь будет оценена по достоинству.

+0

Что вы имеете в виду под «кли tom файл для sqlite "? – CRDave

ответ

0

Прежде всего, добавьте файл ниже в свой проект.

https://github.com/ConnorD/simple-sqlite

Затем создайте database.sqlite файл в ваш проект. База данных содержит первое имя пользователя, фамилию и профиль picutre.

И добавьте ниже код в свой файл AppDelegate.

- (void)createEditableCopyOfDatabaseIfNeeded 
{ 
    // First, test for existence. 
    BOOL success; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    // UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"testing" message:@"path for database" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
    // [alert show]; 
    // [alert release]; 

    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Category_DB.sqlite"]; 

     //NSLog(@"Default writableDBPath: %@",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:@"Category_DB.sqlite"]; 

    //NSLog(@"Default : %@",defaultDBPath); 
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
    // NSLog(@"Success"); 
    if (!success) { 
     NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
    } 
} 

Вызов этого метода в ваш didFinishLaunchingWithOptions

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
[self createEditableCopyOfDatabaseIfNeeded]; 
return NO; 
} 

Теперь запишите ниже код в ваш контроллер представления, где вы хотите использовать запросы.

-(void)databaseOpen 
{ 
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [path objectAtIndex:0]; 
    NSString *myDBnew = [documentsDirectory stringByAppendingPathComponent:@"Category_DB.sqlite"]; 
    myDatabase = [[Sqlite alloc] init]; 
    [myDatabase open:myDBnew]; 
    // NSLog(@"database opened"); 

} 

Для выбора запроса:

[self databaseOpen];  
NSString *query_fetch=[NSString stringWithFormat:@"select Max(session_id) from Report"]; 
NSMutableArray *userData=[[myDatabase executeQuery:query_fetch]mutableCopy]; 

Если вы хотите сохранить изображение в базу данных

-(NSString *) getImagePath{ 
    /* *** Modify on 16 01 2012 by Prerak *** */ 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSError *error; 
    [[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:&error]; 

    return documentsDirectory; 
} 

Если вы хотите, чтобы получить изображение в базу данных

arrProfilepic = [[NSMutableArray alloc]init]; 
    NSError *error = nil; 
    NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]; 

    NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath: stringPath error:&error]; 

    NSLog(@"File Path Array is %@",filePathsArray); 

    for(int i=0;i<[filePathsArray count];i++) 
    { 
     NSString *strFilePath = [filePathsArray objectAtIndex:i]; 
     if ([[strFilePath pathExtension] isEqualToString:@"jpg"] || [[strFilePath pathExtension] isEqualToString:@"png"] || [[strFilePath pathExtension] isEqualToString:@"PNG"]) 
     { 
      NSString *imagePath = [[stringPath stringByAppendingString:@"/"] stringByAppendingString:strFilePath]; 
      NSData *data = [NSData dataWithContentsOfFile:imagePath]; 
      //NSLog(@"Data %@", data); 
      if(data) 
      { 
       UIImage *image = [UIImage imageWithData:data]; 
       NSLog(@"Image %@", image); 
       [arrProfilepic addObject:image]; 
      } 
     } 

    } 
    NSLog(@"profile is %@",arrProfilepic); 

Для вставки запроса:

NSString *documentsDirectory = [self getImagePath];//save image to database 
    NSString *imagePath; 
    imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"User_%d.png",newid]]; 
    NSString *relativePathImage1=nil; 
    NSArray *relativeArray=[imagePath componentsSeparatedByString:@"/Documents"]; 
    UIImage *thumbImage; 
    thumbImage = [VcAddUser.portraitImageView.image imageScaledToFitSize:CGSizeMake(90, 90)]; 
    NSData *thumbData = UIImageJPEGRepresentation(thumbImage, 1.0f); 
       [thumbData writeToFile:imagePath atomically:YES]; 




NSString *query_insert=[NSString stringWithFormat:@"Insert into UserDetails(User_id,User_fname,User_lname,User_image) values(%d,'%@','Smith','%@')",newid,VcAddUser.txtFUsername.text,relativePathImage1]; 
NSMutableArray *userData=[[NSMutableArray alloc]init]; 
userData=[[myDatabase executeQuery:query_insert]; 
[database close]; 

Для Удалить запрос:

NSString *query_user=[NSString stringWithFormat:@" delete from UserDetails where User_id=%d",Userid]; 
     [myDatabase executeNonQuery:query_user]; 
     [myDatabase close]; 


**For Update query:** 

NSString *updatequery=[NSString stringWithFormat:@"Update UserDetails set User_fname='%@',User_lname='%@', User_image='%@' where User_id=%d",txtFUsername.text,txtLUsername.text,relativePathImage1,UseridUpdate]; 
    [myDatabase executeNonQuery:updatequery]; 
    // NSLog(@"Query user is %@",updatequery); 
    [myDatabase close]; 

Для WebServices

-(void) CallWebservice 
{ 
     NSMutableData *responseData = [NSMutableData data]; 
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
     [request setURL:[NSURL URLWithString:@"give your web service url"]]; 
     [request setHTTPMethod:@"POST"]; 
     [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
     [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
     [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]]; 
     NSURLConnection *PostConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
} 


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

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

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    [self removeProgressIndicator]; 
    UIAlertView *alt=[[UIAlertView alloc]initWithTitle:@"Internet connection is not Available!" message:@"Check your network connectivity" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
    [alt show]; 

} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    // check for response only 

    /*NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 

    NSLog(@"%@",responseString);*/ 

    NSError *error; 
    NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; 

    NSLog(@"%@",results); 
} 
+0

Можете ли вы предоставить мне код для веб-сервисов, используя nsurlconnection – BHUMICA

Смежные вопросы