I have been running around the web trying to figure out a way I can send out updates with a new event to the iPhone app I am building. I am pretty sure I can do it with SQLite but I have not found any tutorial that can help. If anyone can give me a clue it will be greatly appreciated.
Now here's a snippet of code
// Create URL and gather parameter's to send to the server's php file
NSString *strURL = [NSString stringWithFormat:#"http://www.yoursite.com/checkForUpdates.php?lastUpdated=%#", lastUpdated];
// Send data to php file
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString: strURL]];
// Store the data returned from the php file
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
After you get your server up in running this is literally all the code you'll need to get started with receiving updates from your server. One way to go about it is to create a database that holds all your update data and the date and time it was added. Create a php file on your server that receives that data(containing the last Update) that we just sent. The php file looks something like this:
<?php
// Database Data
$db_host = 'localhost';
$db_user = 'userName';
$db_pwd = 'password';
// Updates database
$database = 'updates_Database';
// check connection to database
if(!mysql_connect($db_host, $db_user, $db_pwd))
die("Cant connect to database");
// check selection of database
if(!mysql_select_db($database))
die("Can't select database");
// Get values from the URL's(Just requested by app)
$lastUpdated = $_GET['lastUpdated'];
// Query database for updates made after the user's last update
$sql_Query = mysql_query("SELECT * FROM Updates
WHERE dateAdded > '$lastUpdated'");
?>
This will log you into your database, take the data(lastUpdated) you just sent from the app and compare it to the updates in your database. You can then get the data from the query using mysql_fetch_array($sql_Query)
and finally when your all done with your data you can simply go: echo($myData); to send your data back to your app as an NSString As I stated before some devs really like using JSON to accomplish that part because it's very simple and very scaleable, I however don't really need it at the moment. I hope this helps you out man! Let me know if you need some clarification.
Correct me if I'm wrong, you want to be able to check your database for any new updates upon launching, if so, show the user the event in a new view and allow them to add calendar events?
Related
I have been working on an app where the user inputs data stored in core data everyday (two attributes an NSNumber and one as NSDate) and I wanted to improve that by allowing the user to import data from a external file such as csv or any other supported format through a button click. Any suggestions on how to proceed efficiently to do this?
Thank you.
Edit: Just adding a screenshot of the csv file as well as the output of the csv parser as NSArray. Basicly need to fetch the attribute separately and store them in core data on button click.
- The input file as csv:
- Sample csv parser output(NSarray):
I needed to achieve something similar recently.
A couple of members of my project team wanted to take our app prototype out to show potential clients, but wanted to show different data to each client. We solved this by allowing members of our project team to create their own test data before meeting with the client.
I achieved this by creating an example .csv file and distributing it to the other guys in the project team. They populate it with their own test data and use iTunes File Sharing to drop the .csv test data file on to the device.
On load, the app scans its Documents directory for a the test data file. If it exists, it parses the .csv file and persists to the database.
For the CSV parsing, I used Dave DeLong's CHCSVParser: https://github.com/davedelong/CHCSVParser
Plenty of help is available on setting up iTunes file sharing for your app. A quick Google finds this tutorial (http://www.raywenderlich.com/1948/how-integrate-itunes-file-sharing-with-your-ios-app) which should help you out, if you need it.
Edit- added help on storing data from .csv in Core Data
You stated in your original post that you store an NSNumber and NSDate. Taking that as a starting point, you might have a .csv file in the following form:
+----------------+--------------+
+ NSNumberColumn | NSDateColumn |
+----------------+--------------+
+ 1 | 2013-05-15 |
+ 2 | 2013-06-15 |
+ 3 | 2013-07-15 |
+----------------+--------------+
Assuming the output from the CSV parser is an NSArray of NSArrays, you could create the Core Data objects as follows:
I would create a couple of macros for the column numbers:
#define NSNumberColumn 0
#define NSDateColumn 1
Then iterate over the rows in the .csv file:
NSArray *rows = [NSArray arrayWithContentsOfCSVFile:pathToFile]; //CHCSVParser specific parsing method
for (NSArray *row in rows)
{
NSString *numberString = [parsedCsvRow objectAtIndex:NSNumberColumn];
NSString *dateString = [parsedCsvRow objectAtIndex:NSDateColumn];
NSNumber *number = // parse numberString to an NSNumber. Plenty of other posts on achieving this.
NSDate *date = // parse NSDate from dateString. Plenty of other posts on achieving this.
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *myCoreDataObject = [NSEntityDescription insertNewObjectForEntityForName:#"MyCoreDataObject" inManagedObjectContext:context];
[myCoreDataObject setValue:number forKey:#"NSNumberColumn"];
[myCoreDataObject setValue:date forKey:#"NSDateColumn"];
NSError *error;
if (![context save:&error]) {
NSLog(#"%#", [error localizedDescription]);
}
}
Note: Input validation and null checks have been ommited for brevity. I have also taken the liberty of making up your NSManagedObject property names, this will need updating. The above code should be separated in to a more suitable class structure.
I'm not at a Mac right now, so unfortunately I can't check if this works.
Hope that helps.
Try to use plist or json, they are already supported on iOS instead of CSV. CSV would require an third party parser. Using json or plist you will only need to loop throught the elemnts of the collections to create you persistent store. If you have just the CSV you can do a mid conversion using different free tools that you can find for free on the internet and later add to your bundle or publish to your site.
Here's what you do when you already have your CSV file parsed and data is ready to use in Objective-C.
Create a separate context for the import. You don't know how big the data can be, so you probably don't want to block one of your existing contexts while importing.
Iterate through the entries in the parsed data and insert new managed objects configured from each entry.
Every 200, 500, or 1000 entries (different for everybody, you'll need to test what's working best for you) save the context and, if needed, post a notification that a batch has been imported.
To keep the memory low, reset the context and forget all the objects that you created in this import context.
After the loop is finished, don't forget to save the last time.
Now how do you bring the data into another context, say, UI context?
This depends on the way you organized your Core Data stack. For example, import context can be configured as a child of the UI context. In this case, after each save to the import context the changes will be pushed to the UI context (and don't forget to save the UI context as well to push changes further).
But this is not the most efficient approach, because UI context, which is a context on the main thread, is involved in the import, and additional work is done on the UI thread that blocks it. I recommend creating the import context not as a child, but connected to the persistent store coordinator directly. To bring changes to the UI context in this case you either need to call mergeChangesFromContextDidSaveNotification: method after each save or you just refetch in the UI context after each save and in the end. The latter is easier on the UI context and particularly on NSFetchedResultsController, if you use it, because it doesn't need to replay changes to the updated objects one-by-one.
I'm currently developing an app that will be used as track and trace app. This app will need data that is located on a server. Let's say, we create a file for each customer on the server. This file will contain the track and trace info. Would it be easier if this is a xml file or text file and how would the code look like?
Let's say we've already knew the customers number and the file has the same name as the customer number. The user tapped the button to get the data. Then the app contacts the server asking for the file that got the same customers number and reads it presenting the info in a label or something similar.
Any suggestions where to start?
If you dont have any other specific requirements fetching xml files from server will be good enough. For example if you have file at url www.test.com/user1.xml you can load into data
NSData *tmpData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"www.test.com/user1.xml"] ];
//convert data to string
NSString *tmpString = [[NSString alloc] initWithData:tmpData encoding:NSUTF8StringEncoding];
NSArray *piecesArray = [tmpString componentsSeparatedByString:#" "];
if(piecesArray.count==2)
{
labelA.text = [piecesArray objectAtIndex:0];
labelB.text = [piecesArray objectAtIndex:1];
}
My app is on App Store and in its new version I have updated the schema, like number of columns has been changed and name of columns has been changed. But now when I uploaded the new version on App Store, the app is crashing.
I came to know that this is happening because I have changed the schema. I have use SQLite so is there any solution to this problem?
SQLite supports a 'version' when you open (or create) the DB. This is a unique value that you decide. When you change the schema you should change the 'version' string so that the old database is abandoned for a new one. In the same way you would handle creating the database on first setup, you must then also manually migrate any important data from the previous database to the new one.
Unfortunately there's no way to role back an app to the last good version, the best you can do is to remove your app from the store for a few days until you get a fix into place.
Try like this.
Check the version
If new then - if you want Fetch all data from old DB
and remove the old DB. else
no changes
Create new db
Insert data what get from old DB
NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:dbName];
BOOL dbSuccess = [fileManager fileExistsAtPath:dbPath];
if (dbSuccess) {
NSDictionary *oldDetailsDict = [NSDictionary dictionaryWithContentsOfFile:writablePath];
if(![[oldDetailsDict valueForKey:#"version"] isEqualToString:Current_APP_VERSION]){
NSString *oldVersion = [oldDetailsDict valueForKey:#"version"];
if ([oldVersion isEqualToString:Current_APP_VERSION]) {
//no code change needed
}else{
//Get data from old db
//Data moved to array
NSArray *oldDataArray = [Product getDataFromDatabase];
//Remove the old Database
NSString *deletePath = [documentsDirectory stringByAppendingPathComponent:#"sample.sqlite"];
[fileManager removeItemAtPath:deletePath error:nil];
//Create the new DB for new version
[self createdatabase];
//Again Insert the old data to new db
for (Product *pro in oldDataArray) {
[pro insertToDB];
}
}
}
}
i want to take the backup of all the data in the database of my iphone app in dropbox and restore it later.here the main problem is there is too much data in the app so if i am using sql queries to fetch data from sqlite3 database and storing it into the file and again reading data from that file and inserting it to database.can anyone suggest that how can i improve that or what is the best way to do that?
I presume that you mean that you want to be able to restore the data after user has somehow deleted the application and re-installed it again. Since each application has its influence inside the bounds of its sandbox, the only sane option would be to use server. In regards to simply answering your question - there is no way to do it as you've described.
You can use iCloud.
Go to your app manager on Itunes Connect to generate a iCloud Key.
So, all data will be stored on icloud.
You can use too a uuid as Key for your webservice. So, if the use delete app and when he reinstall, you cad download all data with key identifier.
For example:
uuid = [[UIDevice currentDevice] uniqueGlobalDeviceIdentifier];
With Class for UUID
Important: Use the global mode because it allows to use the uuid between applications.
my dropbox-based Sync API solution:
- (IBAction)onTouchDropboxBackup:(id)sender {
DBAccount *account = [[DBAccountManager sharedManager] linkedAccount];
if (account) {
if (![sharedDelegate filesystem]) {
DBFilesystem *filesystem = [[DBFilesystem alloc] initWithAccount:account];
[DBFilesystem setSharedFilesystem:filesystem];
[sharedDelegate setFilesystem:filesystem];
[filesystem release];
}
DBPath *destination = [[DBPath root] childPath:kDataDBFileName];
DBError *error = nil;
//check presense
DBFile *file = [[DBFilesystem sharedFilesystem] openFile:destination
error:&error];
if (error){//not present
[[DBFilesystem sharedFilesystem] createFile:destination
error:&error];
file = [[DBFilesystem sharedFilesystem] openFile:destination
error:&error];
}
if (!error) {
[file writeContentsOfFile:[DOCUMENTS_DIR stringByAppendingPathComponent: kDataDBFileName]
shouldSteal:NO
error:&error];
[file update:&error];
[file close];
}
}else
[[DBAccountManager sharedManager] linkFromController:self];
}
I'm developing an application for iPhone as my master thesis and it is my first experience with programming.
I'm doing an app that will scan barcode, taking ouf from code digits behind it, and then I need to send them to open source database and receive an answer with list of ingredients back.
So this info I found on one internet site.
The question is how I can implement THIS into my program?
It is possible to open the EAN database access from your own applications out of an EAN-query to perform.
This should happen with a simple HTTP GET request, the following format:
http://openean.kaufkauf.net/?ean = [ean] & & cmd = query queryid = [userid]
[Ean] here is the eight-or thirteen-digit EAN to be queried. How do you get a User ID [userid] for the field "queryid" can be found below.
The query was successful, you will receive data in text format (MIME type text / plain) back, which can look like this:
error = 0
name = Natural mineral
bath Vilbeler name = detail RIED source
vendor = H. Krone GmbH & CO.. KG
= maincat drinks, alcohol
subcat =
descr = Natural mineral water carbonated
origin = Germany
= 25% validated
Thanks
You can get the result stored into a string by doing the following
//Replace each var with your strings
NSString *request=[NSString stringWithFormat:#"http://openean.kaufkauf.net/?ean=%#&cmd=%#&queryid=%#%#",EANString,queryString,userIDString,EANString];
NSURL *urequest=[NSURL URLWithString:request];
//Assuming you are using UTF8StringEncoding
NSString *result=[[NSString alloc] initWithContentsOfURL:urequest encoding:NSUTF8StringEncoding error:nil];
//parse the result to get your data
//After you stop using result you can release it
[result release];
If you need further explanation on this let me know.
Edit:
I really don't know about the codes you are using nor about the SDK, though all you need to do after you have your scanner working is to get 3 pieces of data (this to construct your HTTPRequest) and those are EAN, query and userid.
After you have done this you will have to perform the request (first 2 lines of the code) this after you have replaced the values with your recently acquired data (EAN, query and userid).
Then all you have to do is to parse your results; the request will return you a string with the form of the quote from your post, so you will have to go through the string taking whatever you need from it.
Hopefully this was a bit more clear.