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);
}
+(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 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
Im struggling here for a lot,
Im trying to upload an image from iphone to (iis)server folder using webservice asmx(VB.net)
Ive searched a lot and finally used the following code
- (IBAction)btnPostImages_Clicked:(id)sender {
NSMutableURLRequest *request;
request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:#"http://192.168.0.2/digita/digitacampus.asmx/SaveImage"]];
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"%#\"\r\n",#"recFile",#"image.jpg"]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:dt]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
dt is NSData of image in jpeg representation
and the webmethod as follows
<WebMethod()> _
Public Function SaveImage(ByVal recFile As String) As String
Dim file As HttpPostedFile = HttpContext.Current.Request.Files("recFile")
Dim targetFilePath As String = HttpContext.Current.Server.MapPath("") + file.FileName
file.SaveAs(targetFilePath)
Return file.FileName.ToString()
End Function
Nothing happened
Is the above webmethod correct
I have also tried simply as below
- (IBAction)btnPostImages_Clicked:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://192.168.0.2/digita/digitacampus.asmx/SaveImage"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody:dt];
NSURL *conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
}
I dont know what to do else
whats the mistake that I did
How can I identify the image was successfully uploaded or not
Is the URL correct? I think it should be something like: digitacampus.asmx?op=SaveImage and maybe digitalcampus.asmx
You have to convert the String to an filestream like this for example:
Dim fs As FileStream
fs.Write(System.Convert.FromBase64String(recFile), 0, pdfLength)
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.