Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JSON值未保存到iPhone中的SQLite数据库_Iphone_Objective C_Json_Sqlite - Fatal编程技术网

JSON值未保存到iPhone中的SQLite数据库

JSON值未保存到iPhone中的SQLite数据库,iphone,objective-c,json,sqlite,Iphone,Objective C,Json,Sqlite,我有一个应用程序,其中我通过HTTPPOST方法将数据发布到我的服务器API数据库,并以JSON格式获取响应。我想读取JSON数据并将其保存在SQLite数据库中。我已经通过HTTPPOST方法将数据发布到Web服务器API,但是读取JSON数据并将其保存到数据库中还没有实现 我创建了一个由所有JSON数组对象组成的类 这是.h文件: #import <Foundation/Foundation.h> //TokenID":"Vao13gifem","isError":false

我有一个应用程序,其中我通过HTTPPOST方法将数据发布到我的服务器API数据库,并以JSON格式获取响应。我想读取JSON数据并将其保存在SQLite数据库中。我已经通过HTTPPOST方法将数据发布到Web服务器API,但是读取JSON数据并将其保存到数据库中还没有实现

我创建了一个由所有JSON数组对象组成的类

这是.h文件:

#import <Foundation/Foundation.h>


//TokenID":"Vao13gifem","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"rocky@itg.com","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
这是我的apicontroller.m

#import "apicontroller.h"
#import "Result.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"];

        [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) {
            const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,FirstName,Email,) 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);

            }
            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];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (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
#导入“apicontroller.h”
#导入“Result.h”
#进口
#定义数据库_NAME@“旅程.sqlite”
#定义数据库标题@“旅程”
@实现apicontroller
@合成txtUserName;
@合成TXT密码;
@合成txtfirstName;
@合成txtlast;
@合成txtEmail;
@综合网络数据;
-(NSString*)getWritableDBPath{
NSArray*Path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,是);
NSString*documentsDir=[paths objectAtIndex:0];
返回[documentsDir stringByAppendingPathComponent:DATABASE_NAME];
}
-(void)CreateEditableCopyOfDatabaseIf需要
{
//生存检验
成功;
NSFileManager*fileManager=[NSFileManager defaultManager];
n错误*错误;
NSArray*Path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,是);
NSString*documentsDirectory=[paths objectAtIndex:0];
NSString*writableDBPath=[DocumentsDirectoryStringByAppendingPathComponent:DATABASE_NAME];
NSLog(@“%@”,writeabledbpath);
成功=[fileManager fileExistsAtPath:writableDBPath];
如果(成功)
返回;
//可写数据库不存在,因此将默认数据库复制到
//合适的位置。
NSString*defaultDBPath=[[[NSBundle mainBundle]资源路径]
stringByAppendingPathComponent:数据库_名称];
success=[fileManager copyItemAtPath:defaultDBPath
toPath:writeabledbpath
错误:&错误];
如果(!成功)
{
NSAssert1(0,@)无法创建可写数据库文件,消息为:'%@',
[错误本地化描述];
}
}
-(无效)发送请求
{
UIDevice*设备=[UIDevice currentDevice];
NSString*udid=[设备唯一标识符];
NSString*sysname=[设备系统名称];
NSString*sysver=[设备系统版本];
NSString*模型=[设备模型];
NSLog(@“idis:%@,[设备唯一标识符]);
NSLog(@“系统名称为:%@,[设备系统名称]);
NSLog(@“系统版本为:%@,[设备系统版本]);
NSLog(@“系统型号为:%@,[设备型号]);
NSLog(@“设备方向为:%d”,[设备方向]);
NSString*post=[NSString stringWithFormat:@“Loginkey=%@&密码=%@&设备代码=%@&固件=%@&IMEI=%@],txtUserName.text,txtPassword.text,模型,系统版本,udid];
NSData*postData=[post数据使用编码:NSASCIIStringEncoding allowLossyConversion:是];
NSString*postLength=[NSString stringWithFormat:@“%d”,[postData长度]];
NSLog(@“%@”,postLength);
NSMutableURLRequest*请求=[[[NSMutableURLRequest alloc]init]autorelease];
[请求设置URL:[NSURL URLWithString:@”http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login"]]; 
[请求设置HttpMethod:@“POST”];
[请求设置值:HttpHeaderField的postLength:@“内容长度”];
[请求设置值:@“应用程序/x-www-form-urlencoded”forHTTPHeaderField:@“内容类型”];
[请求setHTTPBody:postData];
NSURLConnection*连接=[[NSURLConnection alloc]initWithRequest:request委托:self];
if(连接){
webData=[[NSMutableData]保留];
NSLog(@“%@”,网络数据);
}
其他的
{
}
}
-(void)连接:(NSURLConnection*)连接DidReceiverResponse:(NSURResponse*)响应
{   
[webData setLength:0];
} 
-(void)连接:(NSURLConnection*)连接didReceiveData:(NSData*)数据
{         
[webData:data];
} 
-(无效)连接:(NSURLConnection*)连接失败错误:(NSError*)错误
{     
[连接释放];
[网络数据发布];
} 
-(无效)连接IDFinishLoading:(NSURLConnection*)连接
{      
NSString*loginStatus=[[NSString alloc]initWithBytes:[webData mutableBytes]长度:[webData length]编码:NSUTF8StringEncoding];
NSLog(@“%@”,登录状态);
NSString*json_string=[[NSString alloc]initWithData:webData编码:NSUTF8StringEncoding];
NSDictionary*结果=[json_字符串JSONValue];
NSArray*值=[result objectForKey:@“result”];
NSMutableArray*结果=[[NSMutableArray alloc]init];

对于(int index=0;index我猜是SQL语句列列表中的尾随逗号导致了错误:

const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,FirstName,Email,) VALUES (?,?,?,?)";
请注意,
电子邮件
之间有一个逗号

尝试:

相反

const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,FirstName,Email,) VALUES (?,?,?,?)";
const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,FirstName,Email) VALUES (?,?,?,?)";