I am working on application where using local database as sqlite.
Where I want to create custom file for sqlite I don't know how to do this.
Any help would be appreciated.
First of all add below file into your project.
https://github.com/ConnorD/simple-sqlite
Then create database.sqlite file into your project. Database contain user first nam,last name and profile picutre.
And add below code into your AppDelegate file.
- (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]);
}
}
Call this method into your didFinishLaunchingWithOptions
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self createEditableCopyOfDatabaseIfNeeded];
return NO;
}
Now write below code into your view controller where you want to use queries.
-(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");
}
For select query:
[self databaseOpen];
NSString *query_fetch=[NSString stringWithFormat:#"select Max(session_id) from Report"];
NSMutableArray *userData=[[myDatabase executeQuery:query_fetch]mutableCopy];
IF you want to save image to database
-(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;
}
IF you want to get image to database
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);
For Insert query:
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];
For Delete query:
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];
For 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);
}
Related
I have 5 buttons. Each button has some value like 1,2,3,4,5 in a string named totalSeats_selected.
I want to save them into a nsstringthat shows result like this:
nsstring * result = [1,2,3,4,5];
These values are to used as request for a web service, so it must be in this format to send total number of seats?
So, how to save all these values in nsstring on button event?
Use like this.Suppose your string is in integer means use Method 1 .otherwise use Method 2(If your value assigned in NSString).
Method 1:
- (IBAction)Savebtnpressed:(id)sender {
NSMutableDictionary *datadict=[NSMutableDictionary dictionary];
[datadict setValue:[NSNumber numberWithInt:[first intValue]] forKey:#"1"];
[datadict setValue:[NSNumber numberWithInt:[second intValue]] forKey:#"2"];
[datadict setValue:[NSNumber numberWithInt:[third intValue]] forKey:#"3"];
[datadict setValue:[NSNumber numberWithInt:[fourth intValue]] forKey:#"4"];
[datadict setValue:[NSNumber numberWithInt:[fifth intValue]] forKey:#"5"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:datadict options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *someURLSetBefore =[NSURL URLWithString:#" url "];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * string1=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",string1);
}
}
Method 2:
- (IBAction)Savebtnpressed:(id)sender {
NSMutableDictionary *datadict=[NSMutableDictionary dictionary];
[datadict setObject:[NSString stringWithFormat:#"%#",FIRST] forKey:#"1"];
[datadict setObject:[NSString stringWithFormat:#"%#",SECOND] forKey:#"2"];
[datadict setObject:[NSString stringWithFormat:#"%#",THIRD] forKey:#"3"];
[datadict setObject:[NSString stringWithFormat:#"%#",FOURTH] forKey:#"4"];
[datadict setObject:[NSString stringWithFormat:#"%#",FIFTH] forKey:#"5"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:datadict options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *someURLSetBefore =[NSURL URLWithString:#" url "];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * string1=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",string1);
}
}
+(id)profilePictureUploadWebService :(NSString*)temp andimage:(NSString*)strimage
{
//NSString *post=[NSString stringWithFormat:#"_UserId=%#&_UserImage=%#",temp,strimage];
NSString *post=#"";
NSString *urlTotal= [ NSString stringWithFormat:#"http://mo.sale.com/as.asmx/SaveUserImage?_UserId=%#&_UserImage=%#",temp,strimage];
NSURL *url= [ NSURL URLWithString:urlTotal];
NSLog(#"urlTotal is =%#",url);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"data is =%#",data);
return (urlData);
}
I'm using Xcode 4.4.1. I have created a simple tabbed based application. And then I want to add navigation controller to the application. Can any one tell me how to do that in Xcode 4.4.1. My current code is like this but it doesn't work.
`
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UIViewController *viewController1 = [[FirstViewController alloc] initWithNibName:#"FirstViewController" bundle:nil];
UIViewController *viewController2 = [[Addbills alloc]initWithNibName:#"Addbills" bundle:nil];
UIViewController *viewController3 = [[CalenderView alloc]initWithNibName:#"CalenderView" bundle:nil];
UIViewController *viewController4 = [[Web alloc]initWithNibName:#"Web" bundle:nil];
UIViewController *viewController5 = [[SecondViewController alloc] initWithNibName:#"SecondViewController" bundle:nil];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:viewController1];
[self.navigationController setNavigationBarHidden:TRUE];
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = #[viewController1,viewController2,viewController3,viewController4,viewController5];
self.window.rootViewController = self.tabBarController;
// self.window.rootViewController =self.navigationController;
[self.window addSubview:navigationController.view];
[self.window makeKeyAndVisible];
return YES;
}
`
and this is my button click event in viewController5
`
- (IBAction)backToPrevious:(id)sender {
[self.navigationController popToRootViewControllerAnimated:TRUE];
}`
Thanks,
Here is how you should do it.
// initialize the tabbar controller
UITabBarController *tabbarController = [[[UITabBarController alloc] init] autorelease];
UIViewController *itemsViewController1 = [[[UIViewController alloc] initWithNibName:#"SomeViewController1" bundle:nil] autorelease];
UINavigationController *itemsNavigationController1 = [[UINavigationController alloc] initWithRootViewController:itemsViewController1];
UIViewController *itemsViewController2 = [[[UIViewController alloc] initWithNibName:#"SomeViewController2" bundle:nil] autorelease];
UINavigationController *itemsNavigationController2 = [[UINavigationController alloc] initWithRootViewController:itemsViewController2];
tabbarController.viewControllers = #[itemsNavigationController1,itemsNavigationController2];
_window.rootViewController = tabbarController;
i have a web service, written in c# which look like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloParam(string param)
{
return "Hello " + param;
}
my code in Xcode look like this:
- (IBAction)getButton:(id)sender {
NSString *urlString = #"http://172.16.43.132/Server/Service1.asmx/HelloParam";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
NSLog(#"Shit");
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
}
}
when i call the method hello world. i receive an answer in xml format. it should be in json.
when i call the second method "helloparam" i get an error: parameter is missing.
could you give me a simple example of how to create a connection and communication between an iPhone and a asp.net web service? thanks in advance
I've been trying to get a string from a plist file into a NSURL for webview.
Either i get 'nil' for the returned value, or nothing (no error in console)
I know something's wrong with this code, but i can't pinpoint it where.
NSString *filePath = #"/path/to/Info.plist";
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
NSString *value;
value = [plistDict objectForKey:#"Link"];
NSString *webStringURL = [value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *URL = [NSURL URLWithString:webStringURL];
[self loadURL:URL];
[self setURLToLoad:nil];
Where did i mess up?
NSString *filePath = #"/path/to/Info.plist";
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
NSString *urlString = [plistDict objectForKey:#"Link"];
NSURL *URL = [NSURL URLWithString:urlString];
[self loadURL:URL];
For your better understanding refer to this site:
http://iphonesdevsdk.blogspot.com/2011/04/plist.html
It may help you in using plist in easy way.