Hi in my application i have stored data in my local database sqlite3. Now i have to upload the data form local database sqlite3 to online server. For retrieving the data i have used the dataDictionary to get all the data form the sqlite3 database. And i have converted the data in json format now the problem is how to pass this json data into my online server.
NSMutableArray *array = [[NSMutableArray alloc] init];
[self openDB];
NSString *sql = [NSString stringWithFormat:#"SELECT * FROM reg"];
const char *query_stmt = [sql UTF8String];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, nil)==SQLITE_OK) {
while (sqlite3_step(statement)==SQLITE_ROW) {
NSMutableDictionary *_dataDictionary=[[NSMutableDictionary alloc] init];
NSString *date = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
field1Str= date;
NSString *customer = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
field2Str = customer;
NSString *code1 = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)];
field3Str = code1;
NSString *code2 = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement,3)];
field4Str = code2;
[_dataDictionary setObject:[NSString stringWithFormat:#"%#",field1Str] forKey:#"Kname"];
[_dataDictionary setObject:[NSString stringWithFormat:#"%#",field2Str] forKey:#"kphone"];
[_dataDictionary setObject:[NSString stringWithFormat:#"%#",field3Str] forKey:#"karea"];
[_dataDictionary setObject:[NSString stringWithFormat:#"%#",field4Str] forKey:#"kcity"];
[array addObject:_dataDictionary];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:array options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *someURLSetBefore =[NSURL URLWithString:#"my url for inserting the data into my online server"];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
// print json:
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
}
I have used this above code to pass my sqlite3 database data to my server. I have print the jsondata in log its coming as a json format data only. Please tell me how to push this data to my online server where I'm missing in the code i have stuck here for very long time its eating my head its not working please help me out.
Thanks.
I suggest that you use some proper framework for HTTP communication. Using Apple's low-level API can be quite tricky.
This is a great framework: https://github.com/AFNetworking/AFNetworking
Related
I'm a beginner in the area to work with database on iOS. However I could find a way to connect to a MySQL database, download and parse the json feed. Now in iOS 9, I can't use NSURLConnection anymore, that's why I have to replace it with NSURLSession. I saw many tutorials for example this here. So far, I was not able to replace it. Because I'm under time pressure, I can't waste more time to do this. Is here anyone who could help me to replace it?
My code looks exactly like this:
- (void)downloadItems
{
// Download the json file
NSURL *jsonFileUrl = [NSURL URLWithString:#"http://myhost.ch/test.php"];
// Create the request
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
// Create the NSURLConnection
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
}
#pragma mark NSURLConnectionDataProtocol Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// Initialize the data object
_downloadedData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the newly downloaded data
[_downloadedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Create an array to store the locations
NSMutableArray *_locations = [[NSMutableArray alloc] init];
// Parse the JSON that came in
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
// Loop through Json objects, create question objects and add them to our questions array
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonElement = jsonArray[i];
// Create a new location object and set its props to JsonElement properties
Location *newLocation = [[Location alloc] init];
newLocation.idS = jsonElement[#"idStatistic"];
newLocation.temp = jsonElement[#"temp"];
newLocation.hum = jsonElement[#"hum"];
newLocation.date_time = jsonElement[#"date_time"];
// Add this question to the locations array
[_locations addObject:newLocation];
}
// Ready to notify delegate that data is ready and pass back items
if (self.delegate)
{
[self.delegate itemsDownloaded:_locations];
}
}
You can try this,
{
NSURL *url = [NSURL URLWithString:#"http://myhost.ch/test.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:theRequest
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
responseDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Result:%#", responseDict);
}];
[task resume];
}
Sorry i am really beginner in IPhone development,i am pulling json data from URL and its pulling and loading data perfectly in UITableView, below is code
- (void)fetchFeed
{
NSString *requestString = #"http://bookapi.bignerdranch.com/courses.json";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
self.session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask =
[self.session dataTaskWithRequest:req
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
self.courses = jsonObject[#"courses"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}];
[dataTask resume];
}
Now i want to add filter by instructors, Can any one tell me how i can do that.
Thanks
GET
GET request is just a matter of appending query strings to the API url, for example:
NSString *format = [NSString stringWithFormat:#"http://www.yourapiurl.com?id=%#","123";
NSURL *url = [NSURL URLWithString:format];
NSLog(#"%#",url);
//Creating the data object that will hold the content of the URL
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
POST
-(NSData *)post:(NSString *)postParams{
//Build the Request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.yourapiurl.com"]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postParams length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postParams dataUsingEncoding:NSUTF8StringEncoding]];
//Send the Request
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
//Get the Result of Request
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
return returnData;
}
usage:
NSString *postString = [NSString stringWithFormat:#"prop1=%#&prop2=%#&prop3=%#",
"value1","value2","value3"];
NSData *JsonData = [self post :postString];
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:JsonData options:NSJSONReadingMutableContainers error:nil];
//then parse the JSON
Hi im trying to insert data to a mysql database. I get new content every time i click on save but the columns in the database don't get the text (From the textview and textfields).
-(IBAction)save:(id)sender{
NSString *rawStr = [NSString stringWithFormat:#"location=%#",address.text,#"&long=%#",longitude.text,#"&lat=%#",lat.text,#"&texten=%#",texten.text];
NSData *data = [rawStr dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"http://url.info/projct/phpFile.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
[self dismissViewControllerAnimated:YES completion:nil];
}
It works when i insert data to database by a webbrowser.
It does not appear that you are setting the request header to indicate that this is form-encoded data. Without this, PHP will not populate $_POST superglobal automatically (also POSTed data will not be reflected in URL). You might want to check php://input to see if you are actually getting the data:
You can do that like this:
$query_string = file_get_contents('php://input');
var_dump($query_string);
I am trying to query my Neo4j database, using the REST API.
I have this working so far without using the Cypher query language to retrieve data,
however, now I need to get nodes which are sorted by 'newest' i.e. unix timestamp DESC.
I have tried to add the query within the HTTP body of the NSMutableURLRequest but I am just getting the HTTP error 405.
Here is my code:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#node/%i", EventsManagerDataURL, creatorID]];
NSLog(#"Connecting to URL: %#", url);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSString *jsonMap = #"{'query' : 'start x = node(4,6,7) return x order by x.datestart,'params' : {}}";
NSData *jsonData = [jsonMap dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", jsonData.length] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (data){
NSLog(#"%s. Data: %#", _cmd, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
} else {
NSLog(#"Error: %#", error.localizedDescription);
}
}];
You're missing a single quote here:
NSString *jsonMap = #"{'query' : 'start x = node(4,6,7) return x order by x.datestart***'***,'params' : {}}";
And actually, it needs to have double quotes:
NSString *jsonMap = #"{\"query\" : \"start x = node(4,6,7) return x order by x.datestart\", \"params\" : {}}";
Test with cURL:
curl -H Accept:application/json -H Content-Type:application/json -X POST -d '{"query" : "start x = node(4,6,7) return x order by x.datestart", "params" : {}}' localhost:7474/db/data/cypher
I want to send a new object created on iOS to a receiving server with a POST method using JSON data type. From what I know about receiving data from the server in iOS, is that all JSON handling was simplified by Apple with the introduction of iOS 5. But in contradistinction to GETting JSON objects, POSTing those isn't really described anywhere I could find ...
The first steps I took to try and solve the problem looked as follows:
//build an info object and convert to json
NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, #"name", language, #"language", nil];
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
// any other things to set in request? or working this way?
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// What to do with NSURLConnection? Or how to send differently?
But I really don't know how to send a JSON object to a server using a POST method at all.
Could anybody please help me out?
I worked it out by trying a bit around, here's my code:
//build an info object and convert to json
NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, #"name", language, #"language", nil];
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
// print json:
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
- (IBAction)txtFetchData2:(id)sender {
NSString *queryString = [NSString stringWithFormat:#"http://example.com/username.php?name=%#", [self.txtName text]];
NSMutableURLRequest *theRequest=[NSMutableURLRequest
requestWithURL:[NSURL URLWithString:
queryString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"Value1", #"Key1",
#"Value2", #"Key2",
nil];
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary
options:NSJSONWritingPrettyPrinted error:&error];
[theRequest setHTTPMethod:#"POST"];
[theRequest addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// should check for and handle errors here but we aren't
[theRequest setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
//do something with error
} else {
NSString *responseText = [[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding];
NSLog(#"Response: %#", responseText);
NSString *newLineStr = #"\n";
responseText = [responseText stringByReplacingOccurrencesOfString:#"<br />" withString:newLineStr];
[self.lblData setText:responseText];
}
}];
}
NSString *strUrl = #"URL";
NSURL *url = [NSURL URLWithString:strUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
// For set postdata in string
NSString *strPatientID = [NSString stringWithFormat:#"%#%#%#%#",self.txtDegit1.text,self.txtDegit2.text,self.txtDegit3.text,self.txtDegit4.text];
NSString *deviceToken = #"";
postString = [NSString stringWithFormat:#"practiceid=%#&email=%#&password=%#&devicetoken=%#",strPatientID,self.txtUsername.text,self.txtPassword.text,deviceToken];
NSMutableData *httpDataBody = [NSMutableData data];
[httpDataBody appendData:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSString *strPostLength = [NSString stringWithFormat:#"%lu",[httpDataBody length]];
if ([httpDataBody length ] > 0){
[request addValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request addValue:strPostLength forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:httpDataBody];
}
urlConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[urlConnection start];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://webstar52.com/demo/webcommunity/work.php"]]];
NSString *post = [NSString stringWithFormat:#"&tag=%#&user_id=%#",#"getcontact",#"10408"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];