How to implement API in my project - iphone

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.

Related

Google Scripts - sending email based on a cell value

This is the code I am currently trying to use to implement an email based on the cell value of C2 (see screenshot of Google sheets below).
function amberwarning() {
// Fetch the combined flow value
var combflowrange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("FloodEWS").getRange("C2");
var combflow = combflowrange.getValue();
// Check combined flow value
if (270 < combflow < 310){
// Fetch the email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Email").getRange("A2");
var emailAddress = emailRange.getValues();
// Send Alert Email.
var subject = 'Amber warning';
var message = 'It is possible that the Egger site will experience flooding in the coming hours. The advice is to be prepared to take action as combined river flows can increase very quickly during storms. Please keep up to date with the latest river levels for Hexham at <https://flood-warning-information.service.gov.uk/station/9006>. The latest flood warnings from the Environment Agency for Hexham are here <https://flood-warning-information.service.gov.uk/warnings?location=+hexham>. The latest MetOffice weather forecast can be found here <https://www.metoffice.gov.uk/weather/forecast/gcy2xzrne#?>. Please use all available information to inform your decision making. You will keep receiving an email as per each refresh of the latest data. The current combined flow from the North and South Tyne is' + combflow;
MailApp.sendEmail(emailAddress,subject,message);
}
}
The current error message I am receiving is "The parameters (number[],String,String) don't match the method signature for MailApp.sendEmail. (line 15, file"
The idea is that:
When cell C2 is between 270 and 310, to send an email 'Amber warning'
When cell C2 is above 310 send an email 'Red warning'
When cell C2 is less than 270, no email
This will hopefully be attached to a trigger to schedule every 15 mins
Any help on how to combine the two emails (or have single codes for each email) would be greatly appreciated.
enter image description here
It seems your "emailAddress" parameter is a number array (number[]) since the error you are receiving says so.
Try using getValue() if it is a single address, or get the first value of getValues() which is a 2D array by doing getValues()[0].
Whichever you choose, assign it to your emailAddress variable before calling MailApp.sendEmail().
Try to follow the steps in the documentation
as it explains everything clearly and how to send email through app-script

Loading text from a file

I am making an Iphone drinking card game app.
All the card mean something different and i want the user to be able to press an info button and then show a new screen with information about the current card. How can i make a document to load text from instead of using a bunch og long strings?
Thanks
You could look into plist files - they can be loaded quite easily into the various collection objects and edited with the plist editor in Xcode.
For instance, if you organize your data as a dictionary, the convenience constructor
+ (id)dictionaryWithContentsOfURL:(NSURL *)aURL
from NSDictionary would provide you with as many easily accessible strings as you need.
This method is useful if you consider your strings primarily data as opposed to UI elements.
Update:
As #Alex Nichol suggested, here is how you can do it in practice:
To create a plist file:
In your Xcode project, for instance in the Supporting Files group, select New File > Resource > Property List
You can save the file in en.lproj, to aid in localization
In the Property list editing pane, select Add Row (or just hit return)
Enter a key name (for instance user1) and a value (for instance "Joe")
To read the contents:
NSURL *plistURL = [[NSBundle mainBundle] URLForResource:#"Property List" withExtension:#"plist"];
NSLog(#"URL: %#", plistURL);
NSDictionary *strings = [NSDictionary dictionaryWithContentsOfURL:plistURL];
NSString *user1 = [strings objectForKey:#"user1"];
NSLog(#"User 1: %#", user1);
A plist, a JSON string, and an SQLite database walked into a bar ...
Oops!! I mean those are the three most obvious alternatives. The JSON string is probably the easiest to create and "transport", though it's most practical to load the entire thing into an NSDictionary and/or NSArray, vs read from the file as each string is accessed.
The SQLite DB is the most general, and most speed/storage efficient for a very large number (thousands) of strings, but it takes some effort to set it up.
In my other answer, I suggest the use of a dictionary if your texts are mostly to be considered as data. However, if your strings are UI elements (alert texts, window titles, etc.) you might want to look into strings files and NSBundle's support for them.
Strings files are ideally suited for localization, the format is explained here.
To read them into you app, use something like this:
NSString *text1 = NSLocalizedStringFromTable(#"TEXT1", #"myStringsFile", #"Comment");
If you call your file Localizable.strings, you can even use a simpler form:
NSString *str1 = NSLocalizedString(#"String1", #"Comment on String1");
A useful discussion here - a bit old, but still useful.

What DB do I use to update events in app?

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?

iOS/iPhone programming. Address book. Extra property for user/contact

I'm developing an iPhone application which uses standard iPhone address book (database) of contacts. I need to add some extra property to contacts but as I see iOS API does not permit addition of extra/custom properties to contacts.
Questions:
1. Is there an ability to deal with extra properties in iOS adressbook API?
2. I need expert's advice about standard approaches of how to store extra data for users/contacts: using SQLite, XML or maybe there is some data store dedicated for every application?
It isn't possible to append custom fields to Address Book records. You should consider looking into Core Data where you can store your custom fields mapped to a record ID.
Add custom property to address book.
The following code listing adds a custom property, and then removes
it:
NSNumber* stringProperty = [NSNumber numberWithInteger:kABStringProperty];
NSString* testProperty = #"com.example.myProperty";
NSDictionary* dict = [NSDictionary dictionaryWithObject:stringProperty
forKey:testProperty];
NSInteger result = [ABPerson addPropertiesAndTypes:dict];
NSLog(#"Added %d properties.", result);
result = [ABPerson removeProperties:[NSArray arrayWithObject:testProperty]];
NSLog(#"Removed %d properties.", result);
More info:
https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AddressBook/Tasks/AddingProperties.html

Is there any way to get the "Me" card from iPhone Address Book API?

So I'm stumped on this one.
In Mac OS X there is an easy way to get the "Me" card (the owner of the Mac/account) from the built-in address book API.
Has anyone found a way to find out which contact (if it exists) belongs to the owner of the iPhone?
You could use the undocumented user default:
[[NSUserDefaults standardUserDefaults] objectForKey:#"SBFormattedPhoneNumber"];
and then search the address book for the card with that phone number.
Keep in mind that since the User Default is undocumented, Apple could change at any time and you may have trouble getting into the App Store.
Another approach you could take, although it is much more fragile, is to look at the device name. If the user hasn't changed it from the default "User Name's iPhone" AND they are using their real name as an iPhone, you could grab the user name from that. Again, not the best solution by any means, but it does give you something else to try.
The generally accepted answer to this question is to file a Radar with Apple for this feature and to prompt users to choose their card.
Contacts container have a me identifier property on iOS that can be accessed using container.value(forKey: "meIdentifier")
if let containers = try? CNContactStore().containers(matching: nil) {
containers.forEach { container in
if let meIdentifier = container.value(forKey: "meIdentifier") as? String {
print("Contacts:", "meIdentifier", meIdentifier)
}
}
The identifier is a legacy identifier used in the old AddressBook framework. You can still access it in CNContact:
let iOSLegacyIdentifier = contact.value(forKey: "iOSLegacyIdentifier")
There is no such API in the iPhone SDK 2.2.1 and earlier. Please file a request for it at: http://bugreport.apple.com
Edit: [Obsolete answer]
There's no API for getting the "me" card because there is no "me" card. The iPhone's contacts app has no way of marking a card as being "me", and the API reflects this.
I came up with a partial solution to this
you can get the device name as follows
NSString *ownerName = [[UIDevice currentDevice] name];
in English a device is originally called, for example, 'Joe Blogg's iPhone'
the break out the name
NSRange t = [ownerName rangeOfString:#"’s"];
if (t.location != NSNotFound) {
ownerName = [ownerName substringToIndex:t.location];
}
you can then take that name and search the contacts
CNContactStore *contactStore = [CNContactStore new];
NSPredicate *usersNamePredicate = [CNContact predicateForContactsMatchingName:usersName];
NSArray * keysToFetch = #[[CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName],CNContactPhoneNumbersKey,CNContactEmailAddressesKey,CNContactSocialProfilesKey, ];
NSArray * matchingContacts = [contactStore unifiedContactsMatchingPredicate:usersNamePredicate keysToFetch:keysToFetch error:nil];
Of course other languages differ in the device name string e.g. 'iPhone Von Johann Schmidt' so more parsing needs to be done for other languages and it only works if the user hasn't changed the name of the device in iTunes to something like "Joes phone' but it gives you a starting point
well... it gives you an array of matching items :) So if there is more than one contact with that array you just have to use pot luck and go with the first one or work thru multiple cards and take what you need from each.
I did say its a partial solution and even though it won't work for all user cases you might find it works for many of your users and reduces a little friction