NSSearchPathForDirectoriesInDomains c++ equivalent - c++

on objectiv-c I have the follow method:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
it return the app folders, on emulator:
/Users/ademar/Library/Application Support/iPhone Simulator/6.0/Applications/78A001F6-DDDE-4F6D-B762-8AAF42F1A1E3/Documents
I need the same on C++ but I'm not finding, have a similar method on c++?

Related

How do I use the version number of a C++ program in the program itself? [duplicate]

I would like to add the current version into the "about" section of my app.
As seen in this attached screenshot Apple offers versioning.
How do you display these settings in your app?
After further searching and testing, I found the solution myself.
NSDictionary* infoDictionary = [[NSBundle mainBundle] infoDictionary];
NSLog(#"%i Keys: %#", [infoDictionary count],
[[infoDictionary allKeys] componentsJoinedByString: #" ,"]);
This snipplet gave me the following output:
20 Keys : NSBundleResolvedPath ,CFBundleVersion ,NSBundleInitialPath ,CFBundleIdentifier ,NSMainNibFile ,CFBundleIconFile ,CFBundleInfoPlistURL ,CFBundleExecutable ,DTSDKName ,UIStatusBarStyle ,CFBundleDevelopmentRegion ,DTPlatformName ,CFBundleInfoDictionaryVersion ,CFBundleSupportedPlatforms ,CFBundleExecutablePath ,CFBundleDisplayName ,LSRequiresIPhoneOS ,CFBundlePackageType ,CFBundleSignature ,CFBundleName
So the solution is as simple as:
NSString *version =[[[NSBundle mainBundle] infoDictionary] valueForKey:#"CFBundleVersion"];
However, this is not the Current Project Version as seen in the screenshot but the Bundle Version of the plist file.
Look into your Info.plist file which should have keys like CFBundleVersion and CFBundleShortVersionString
Those items in the Build Info are not available to your built app. They are placeholders that you could possibly pull into your app. What is in your app is anything that you place in, say, the Resources folder of your app, like any text files, or plists, or a nice picture of your versioning engineer.
Now, you could pull some of the items in the Build Info window into a info.plist, using special identifiers, such as ${VERSION_INFO_PREFIX} or other token. The tokens are available if you click on any of the items on the left hand side in the window you have included above. For example, click on the word "Current Project Version" and copy the token that you see at the bottom, "CURRENT_PROJECT_VERSION". Then go to your plist file, and add an entry. Give it any name you want or "Current Project Version". Paste in ${CURRENT_PROJECT_VERSION} on the right hand side. Now that value is available to you from your app, programmatically. Of course, someone now has to enter that value into the appropriate place either in the Build Info window or elsewhere. It might just be easier just to manage this and fields like this in the info.plist file. It's up to you how you'd like to handle these things.
Here is how I get version info out of my info.plist:
+ (NSString *) getAppVersionNumber;
{
NSString *myVersion,
*buildNum,
*versText;
myVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleShortVersionString"];
buildNum = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey];
if (myVersion) {
if (buildNum)
versText = [NSString stringWithFormat:#"Version: %# (%#)", myVersion, buildNum];
else
versText = [NSString stringWithFormat:#"Version: %#", myVersion];
}
else if (buildNum)
versText = [NSString stringWithFormat:#"Version: %#", buildNum];
NSLog(versText);
return versText;
}
NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] valueForKey:#"CFBundleVersion"];
returns me always the same value(initial version) even if i change the version from the project settings but.
NSString * appVersionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleShortVersionString"];
does the trick.
For the lazy here is the swift version :
NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString")!
NSBundle.mainBundle.infoDictionary[#"CFBundleShortVersionString"];

ios NSRegularExpression trouble

I'm trying to do a basic regular expression in xcode and it's not cooperating.
NSString *urlString = #"http://www.youtube.com/v/3uyaO745g0s?fs=1&hl=en_US";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"/.*?v=(.*)&.*/" options:NSRegularExpressionCaseInsensitive error:&error];
NSTextCheckingResult *fmis = [regex firstMatchInString:urlString options:0 range:NSMakeRange(0, [urlString length])];
if(fmis) {
NSRange match = [fmis range];
NSLog(#"%i", match.location);
}
essentially, I'm just trying to suck 3uyaO745g0s out of the urlString. I assume a regular expression is the best way? Thanks for looking my question.
** EDIT **
sometimes the url will look like this: http://www.youtube.com/watch?v=3uya0746g0s and I have to capture the vid from that as well.
I think it's much easier to create an NSURL object and let it do its magic for you:
NSString *urlString = #"http://www.youtube.com/v/3uyaO745g0s?fs=1&hl=en_US";
NSURL *url = [NSURL URLWithString:urlString];
// Since you're targeting the last component of the url
NSString *myMatch = [url lastPathComponent]; //=> 3uyaO745g0s
You can find more on how to access various parts of an NSURL object here
There are many types of Youtube URLs.
Maybe you can try this
NSString *urlString = #"http://www.youtube.com/v/3uyaO745g0s?fs=1&hl=en_US";
NSString *regEx = #"[a-zA-Z0-9\\-\\_]{11}";
NSRange idRange = [urlString rangeOfString:regEx options:NSRegularExpressionSearch];
NSString *youtubeID = [urlString substringWithRange:idRange];
I found this regular expression here. And you don't have to use NSRegularExpression for simple search:)
I think this is pretty good solution but if you want more reliable result, then try another regular expression in that answer.

Create Order to Spree ecommerce using iOS app

In my app, i want to order a product in spree e-commerce by iPhone app. I easily get the products name and their detail but while creating order for products it's return the error in html page :
<h1>
TypeError
in Spree::Api::V1::OrdersController#create
</h1>
<pre>can't convert Symbol into Integer</pre>
I m sending post request as:
NSString *str = [NSString stringWithFormat:#"http://localhost:3000/api/orders"];
NSURL *urlForBuy = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:urlForBuy];
NSString *idVariant = [NSString stringWithFormat:#"order[line_items][%d][variant_id]",0];
NSString *qnty = [NSString stringWithFormat:#"order[line_items][%d][quantity]",0];
NSString *idVariantValue = #"123456";
[request setPostValue:[NSString stringWithFormat:#"%d",[idVariantValue intValue]] forKey:idVariant];
[request setPostValue:[NSString stringWithFormat:#"%d",1] forKey:qnty];
[request setPostValue:#"<my admin token>" forKey:#"token"];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(buyResponse:)];
[request setDidFailSelector:#selector(buyResponse_failed:)];
[networkQueue addOperation:request];
[networkQueue go];
Also, this url i get from REST api documentation of Spree which is: http://guides.spreecommerce.com/rest.html
Another thing I want to know what is [line_items] in this url... Also if their is any tutorial apart from above url?...Thanks in advance.
Orders are created through the API by passing in line items as shown in this test.
api_post :create, :order => {
:line_items => [
{
:variant_id => variant.to_param,
:quantity => 5
}
]
}
The line_items parameter is expected to be an array of hashes, consisting of a variant_id and a quantity field. The documentation says the request looks like this:
POST /api/orders?order[line_items][0][variant_id]=1&order[line_items[0][quantity]=5
I hope that helps you understand it better!

Using OpenCV FileStorage on iOS

I am creating an object classifier using OpenCV and to avoid having to train the classifiers every time the app is launched I would like to somehow store them in a file. The most convenient way available seems to be using OpenCVs FileStorage class.
I gave this a shot but it didn't seem to work. The saved file did not show up anywhere though I did not receive an error. I suppose iOS doesn't just let you save any file. An alternative way would be to retrieve the YAML as a string, convert it to an NSString and save it in a property list, but I am not sure how this can be done or whether it is even possible.
Any help would be greatly appreciated.
I managed to get the FileStorage class working with iOS. The problem was that I needed to make sure the file was being created in iOSs designated Documents Directory. Here is some sample code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString *vocabPath = [docs stringByAppendingPathComponent:#"vocabulary.xml"];
FileStorage fs([vocabPath UTF8String], FileStorage::WRITE);
// vocab is a CvMat object representing the vocabulary in my bag of features model
fs << "vocabulary" << vocab;
fs.release();
// READING
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString *vocabPath = [docs stringByAppendingPathComponent:#"vocabulary.xml"];
FileStorage fs([vocabPath UTF8String], FileStorage::READ);
// vocab is a CvMat object representing the vocabulary in my bag of features model
fs["vocabulary"] >> vocab;
fs.release();

How to Store the game score in android cocos2d

I calculates the score in game project using android cocos2d, in that game after finishing the first level it goes to the next level, so i want to store that first level score and also add next level scores. how can i store that scores in android-cocos2d.
Use NSKeyedArchiver class to store, here you have an example:
------------- WRITE
// get allowed save paths
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// string for the default path
NSString *documentsDirectory = [paths objectAtIndex:0];
// full path plus filename for save game
NSString *gameStatePath = [documentsDirectory stringByAppendingPathComponent:#"gameState.dat"];
// storage for game state data
NSMutableData *gameData = [NSMutableData data];
// keyed archiver
NSKeyedArchiver *encoder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:gameData];
// encode all variables we want to track
[encoder encodeObject:[player inventoryDict] forKey:#"playerInventoryDict"];
[encoder encodeObject:[player equippedDict] forKey:#"playerEquippedDict"];
[encoder encodeInt:[player initialActionPoints] forKey:#"playerInitialActionPoints"];
[encoder encodeInt:[player actionPoints] forKey:#"playerActionPoints"];
[encoder encodeInt:[player experiencePoints] forKey:#"playerExperiencePoints"];
[encoder encodeInt:[player xpNextLevel] forKey:#"playerXPNextLevel"];
[encoder encodeBool:[player isThinking] forKey:#"playerIsThinking"];
// finish, write and release the encoder
[encoder finishEncoding];
[gameData writeToFile:gameStatePath atomically:YES];
[encoder release];
----------------- READ
// get allowed save paths
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// string for the default path
NSString *documentsDirectory = [paths objectAtIndex:0];
// full path plus filename for save game
NSString *gameStatePath = [documentsDirectory stringByAppendingPathComponent:#"gameState.dat"];
// storage for game state data
NSMutableData *gameData = [NSMutableData data];
// start the decoder
NSKeyedUnarchiver *decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:gameData];
// start with player data
PlayerEntity *player = [PlayerEntity player];
// variables from the PlayerEntity Class
player.inventoryDict = (NSDictionary *)[decoder decodeObjectForKey:#"playerInventoryDict"];
player.equippedDict = (NSDictionary *)[decoder decodeObjectForKey:#"playerEquippedDict"];
player.initialActionPoints = [decoder decodeIntForKey:#"playerInitialActionPoints"];
player.actionPoints = [decoder decodeIntForKey:#"playerActionPoints"];
player.experiencePoints = [decoder decodeIntForKey:#"playerExperiencePoints"];
player.xpNextLevel = [decoder decodeIntForKey:#"playerXPNextLevel"];
player.isThinking = [decoder decodeBoolForKey:#"playerIsThinking"];
// release the decoder
[decoder release];
Original code from HERE
sounds like what you're actually asking for here is how to store data for an app, which is technically nothing to do with cocos2d, as that's just a 2d rendering/graphics engine.
you could either create a customer content provider for your app which will give you a database to store your data in, however this approach is generally best suited for when you want other apps to be able to access your applications data. You could also use, for a more quick and dirty approach, a SharedPreferences approach.
android persistence is described well here
for a simply handle the score : you can use the static variable like "static int myscore ;" and apply some logic on it otherwise use the sqlite for handling the score event ....!!!!
I am guessing if you are using cocos2d for android port in java, this answer above in objective C might not be immediately useful to you. Here are some thought.
First, the simple approach is to create a database which you can read and write score data to . This will be the same as any android app.
There is a cocos2d android application thats been open sourced and which implements this ..
http://denvycom.com/blog/step-by-step-guide-on-how-to-build-your-first-slider-puzzle-game-in-cocos2d-for-android-part-1/
A specific example can be found here ...
https://github.com/chuvidi2003/GidiGames/blob/master/src/com/denvycom/gidigames/PuzzleLayer.java
mDbHelper = new DbAdapter(appcontext);
mDbHelper.open();
String labelmoves;
Cursor ScoreCursor = mDbHelper.fetchPuzzleBest("puzzlemania", GidiGamesActivity.currentpuzzletype,String.valueOf(NUM_ROWS)); // mDbHelper.fetchBestScore("puzzlemania", "");
if(ScoreCursor.getCount() > 0){
ScoreCursor.moveToFirst();
labelmoves = ScoreCursor.getString(ScoreCursor.getColumnIndex(
DbAdapter.KEY_GAME_MOVES)) ;
}
The above simple extracts some "moves" data from a database.
A similar approach can be used to also save data to a database .
See link below to learn more about database interaction in android
http://developer.android.com/training/basics/data-storage/databases.html
Best.