Hello I believe that this is a simple issue, I'm a newbie in objective c so please help me.
I have a populated data in plist and i want to make a simple search ( uitextfield and uibutton) how will i make this? Here's my plist:
<plist version="1.0">
<array>
<dict>
<key>ID</key>
<integer>0</integer>
<key>title</key>
<string>Toyota Gen. Santos</string>
<key>address</key>
<string>National Hwy., City Heights, General Santos City, South Cotabato</string>
<key>tel</key>
<string>(083) 554 2994</string>
<key>latitude</key>
<real>6.119086</real>
<key>longitude</key>
<real>125.159881</real>
<key>img</key>
<string>locator_gmap_marker.png</string>
</dict>
....
</array>
</plist>
Thanks! Here's my method for loading plist
//read plist
-(NSString *) dataFilePath{
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [path objectAtIndex:0];
return [documentDirectory stringByAppendingPathComponent:#"locations.plist"];
}
- (void)readPlist{
//read plist
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
NSLog(#"%#\n",array);
}
}
The [self readPlist] will be placed at the veiwDidLoad method. the output will be seen at the NSLOG - all item I have stored in the plist. What i hope to achieved is to get a specific data by searcheing on a UITextfield with a UIbutton and will be seen at a UIlabel.
This code to iterate the dictionaries from the plist i got it from this How to search in a plist to retrieve a value for a specific key, here's the code from event button:
//event button
//Read locations details from plist
NSString *path = [[NSBundle mainBundle] pathForResource:#"locations" ofType:#"plist"];
NSArray *locations = [NSArray arrayWithContentsOfFile:path];
for (NSDictionary *row in locations){
NSNumber *tel = [row objectForKey:#"tel"];
NSNumber *address = [row objectForKey:#"address"];
NSString *title = [row objectForKey:#"title"];
self.titleLbl.text = title;
self.addrsLbl.text = address;
self.telLbl.text = tel;
}
Here's the code i remade in event button. Thanks to
Bijoy Thangaraj, Tark for reference and rmaddy for helping out.
How to search in a plist to retrieve a value for a specific key
Search on Arrays inside Plist in Xcode
- (IBAction)eventSearch:(UIButton *)sender {
//Read locations details from plist
NSString *path = [[NSBundle mainBundle] pathForResource:#"locations" ofType:#"plist"];
NSArray *locations = [NSArray arrayWithContentsOfFile:path];
//convert string to number
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *IDnum = [f numberFromString:self.idTxtField.text];
for (NSDictionary *row in locations) {
NSNumber *itemID = [row objectForKey:#"ID"];
if(IDnum == itemID){
NSString *tel = [row objectForKey:#"tel"];
NSString *address = [row objectForKey:#"address"];
NSString *title = [row objectForKey:#"title"];
self.titleLbl.text = title;
self.addLbl.text = address;
self.telLbl.text = tel;
}
}
NSLog(#"accessed!");
self.idTxtField.text = #"";
}
Related
I want to share contact by using whatsapp from my app.
I create vcf file and sent it UIActivityViewController.
However whatsapp says ; This item cannot be shared. Please select different item
I used code is that:
- (NSString *)vCardRepresentation:(NSString*)message
{
NSArray *arr=[message componentsSeparatedByString:#","];
NSString *fname,*image,*phone,*Email;
fname=[arr objectAtIndex:0];
phone=[arr objectAtIndex:1];
Email=[arr objectAtIndex:2];
image=[arr objectAtIndex:3];
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
[mutableArray addObject:#"BEGIN:VCARD"];
[mutableArray addObject:#"VERSION:3.0"];
[mutableArray addObject:[NSString stringWithFormat:#"N:;Alper KOC;;;"]];
[mutableArray addObject:[NSString stringWithFormat:#"FN:Alper KOC"]];
[mutableArray addObject:[NSString stringWithFormat:#"TEL;type=CELL;type=VOICE;waid=905416050594:+90 541 605 0594"]];
[mutableArray addObject:#"END:VCARD"];
NSString *string = [mutableArray componentsJoinedByString:#"\n"];
return string;
}
NSString * strVCard = [self vCardRepresentation:message.message];
NSError * err;
[strVCard writeToFile:[NSString stringWithFormat:#"%#/%#",documentsDirectory,#"data.vcf"] atomically:YES encoding:NSUTF8StringEncoding error:&err];
[items addObject:[NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/%#",documentsDirectory,#"data.vcf"]]];
self.activityViewController = [[customactivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
[self presentViewController:self.activityViewController animated:YES completion:nil];
Please Use CNContactVCardSerialization For VCARD Generating.
I have a UITextField as following:
_itemTextField = [[UITextField alloc];
This UITextField may contain item number only ex: "11321" or item number and size ex: "11321-XS" or "12355-40".
I want to extract the item and size (if it's available) separately in two different variables, as following:
NSString *itemNumber = #"11321";
NSString *itemSize = #"XS";
Please advise.
NSString *str = #"11115-ex";
if([str containsString:#"-"]){
NSArray * arr =[str componentsSeparatedByString:#"-"];
NSString *first = [arr objectAtIndex:0];
NSString *second = [arr objectAtIndex:1];
NSLog(#"Return String %# %#",first,second);
}
else
{
NSLog(#"Return String %#",str);
}
I've been trying to convert a Quiz app that was based for Mac OS to iOS because I liked the idea of loading all questions from a single .txt file.
I'm still pretty new in the Objective-C language as I've used C# before.
The questions and answers are loaded via this function:
- (void)loadQuestionsAndAnswersArray {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Quiz1" ofType:#"txt"];
NSString *textFileString = [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:NULL];
NSArray *seperatedQA = [textFileString componentsSeparatedByString:#"\n\n"];
for (NSString *QA in seperatedQA) {
NSString *questionString = [[[QA componentsSeparatedByString:#"\n"] objectAtIndex:0] stringByReplacingOccurrencesOfString:#"Q:" withString:#""];
NSMutableArray *answers = [[QA componentsSeparatedByString:#"A:"] mutableCopy];
[answers removeObjectAtIndex:0];
int correctAnswerLoc = 0;
for (int i = 0; i < answers.count; i++) {
NSString *answer = [answers objectAtIndex:i];
NSString *editedAnswer = [answer stringByReplacingOccurrencesOfString:#"\n" withString:#""];
editedAnswer = [editedAnswer stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[answers removeObjectAtIndex:i];
[answers insertObject:editedAnswer atIndex:i];
answer = editedAnswer;
if ([answer rangeOfString:#"[CORRECT]"].location != NSNotFound) {
correctAnswerLoc = [answers indexOfObject:answer];
NSString *editedAnswer = [answer stringByReplacingOccurrencesOfString:#"[CORRECT]" withString:#""];
[answers removeObjectAtIndex:i];
[answers insertObject:editedAnswer atIndex:i];
}
}
NSLog(#"answers = %#", answers);
NSDictionary *QADictionary = [NSDictionary dictionaryWithObjectsAndKeys:questionString, #"question", answers, #"answers", [NSNumber numberWithInt:correctAnswerLoc], #"correctAnswerLocation", nil];
[questionsAndAnswers addObject:QADictionary];
}
resultsArray = [[NSMutableArray alloc] initWithCapacity:[questionsAndAnswers count]];
}
The app then has a text field for the question and then 3 buttons, one for each answer. And when a new questions appears it changes the text within the text field and the title of the buttons.
This code works like a charm on the Mac App but on the iOS version it's like it can't find the txt file, the buttons etc is left blank.
I've been sitting on this for a week or so about now and that's the reason for this post.
The iOS app is based on this Github Mac app: https://github.com/SquaredTiki/Quizzer
If you want to have a look at how I've tried to convert the app here's a link to that to:
https://www.dropbox.com/s/1jqz9ue97p3v2h1/iTrafikk.zip?dl=0
And of course I'm not asking you to solve the whole issue for me, maybe just push me in the right direction if possible :)
I checked your project. And it seems that you are not calling loadQuestionsAndAnswersArray anywhere in your code. Also you are not initializing the questionsAndAnswers anywhere in the project.
Change your code like:
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadQuestionsAndAnswersArray];
}
- (void)loadQuestionsAndAnswersArray
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Quiz1" ofType:#"txt"];
NSString *textFileString = [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:NULL];
NSArray *seperatedQA = [textFileString componentsSeparatedByString:#"\n\n"];
for (NSString *QA in seperatedQA)
{
NSString *questionString = [[[QA componentsSeparatedByString:#"\n"] objectAtIndex:0] stringByReplacingOccurrencesOfString:#"Q:" withString:#""];
NSMutableArray *answers = [[QA componentsSeparatedByString:#"A:"] mutableCopy];
[answers removeObjectAtIndex:0];
int correctAnswerLoc = 0;
for (int i = 0; i < answers.count; i++)
{
NSString *answer = [answers objectAtIndex:i];
NSString *editedAnswer = [answer stringByReplacingOccurrencesOfString:#"\n" withString:#""];
editedAnswer = [editedAnswer stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[answers removeObjectAtIndex:i];
[answers insertObject:editedAnswer atIndex:i];
answer = editedAnswer;
if ([answer rangeOfString:#"[CORRECT]"].location != NSNotFound)
{
correctAnswerLoc = [answers indexOfObject:answer];
NSString *editedAnswer = [answer stringByReplacingOccurrencesOfString:#"[CORRECT]" withString:#""];
[answers removeObjectAtIndex:i];
[answers insertObject:editedAnswer atIndex:i];
}
}
NSLog(#"answers = %#", answers);
NSDictionary *QADictionary = [NSDictionary dictionaryWithObjectsAndKeys:questionString, #"question", answers, #"answers", [NSNumber numberWithInt:correctAnswerLoc], #"correctAnswerLocation", nil];
if (!questionsAndAnswers)
{
questionsAndAnswers = [[NSMutableArray alloc] init];
}
[questionsAndAnswers addObject:QADictionary];
}
resultsArray = [[NSMutableArray alloc] initWithCapacity:[questionsAndAnswers count]];
[self loadQuestionsAndAnswersIntoInterface];
}
Okay so after feedback I am doing this changes to my code it's working but just adding and replacing the first one?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *user_id = [prefs objectForKey:#"user_id"];
NSString *fixture_id = [prefs objectForKey:#"fixture_id"];
// Get path to documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
if ([paths count] > 0)
{
NSString *selectedPath = [[paths objectAtIndex:0]
stringByAppendingPathComponent:[NSString stringWithFormat:#"%#-%#",user_id, fixture_id]];
// Read both back in new collections
self.mySelectionsArray = [NSArray arrayWithContentsOfFile:selectedPath];
NSLog(#"Players Selected = %#", self.mySelectionsArray);
}
NSDictionary *tempDic = [[[self.listOfPlayersArray objectAtIndex:indexPath.section] objectForKey:#"contacts"] objectAtIndex:indexPath.row];
NSString *avatar = [tempDic objectForKey:#"avatar"];
NSString *avatarSmall = [tempDic objectForKey:#"avatar_small"];
NSString *first_name = [tempDic objectForKey:#"first_name"];
NSString *last_name = [tempDic objectForKey:#"last_name"];
NSDictionary *innerDic;
innerDic = [NSDictionary dictionaryWithObjects:
[NSArray arrayWithObjects: avatar, avatarSmall, first_name, last_name, nil]
forKeys:[NSArray arrayWithObjects:#"avatar", #"avatar_small", #"first_name", #"last_name", nil]];
self.mySelectionsArray = [NSMutableArray arrayWithObject:[NSDictionary dictionaryWithDictionary:innerDic]];
// [self.mySelectionsArray insertObject:innerDic atIndex:0];
[self.mySelectionsArray addObject:innerDic];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if ([paths count] > 0)
{
// Path to save array data
NSString *arrayPath = [[paths objectAtIndex:0]
stringByAppendingPathComponent:[NSString stringWithFormat:#"%#-%#",user_id, fixture_id]];
NSLog(#"Path: %#",arrayPath);
// Write array
[self.mySelectionsArray writeToFile:arrayPath atomically:YES];
}
[self dismissViewControllerAnimated:YES completion:nil];
}
Which is now checking for array and pulling it down then adding the object
The plist looks like this after selecting a player;
{
"first_name" = Ollie;
"last_name" = Akroyd;
},
{
"first_name" = Ollie;
"last_name" = Akroyd;
}
)
Stated your code, mySelections is empty, I guess you want to add innerDic to it; moreover you are saving mySelections instead of userSelections.
You should add innerDic to mySelections and save userSelections to resolve your issue.
EDIT
Instead of
self.mySelectionsArray = [NSMutableArray arrayWithObject:[NSDictionary dictionaryWithDictionary:innerDic]];
which overrides the read array, add the object:
[self.mySelectionsArray addObject:innerDic];
self.mySelectionsArray must be mutable, so instead of
self.mySelectionsArray = [NSArray arrayWithContentsOfFile:selectedPath];
write
self.mySelectionsArray = [[NSArray arrayWithContentsOfFile:selectedPath] mutableCopy];
What I want to do is to populate a pickerView from an array based on a .plist, which can be added to from a textField. I've got it to work, but it only adds one key and replaces it when a new one is added. For instance if I add "hello", and then try to add another one, it replaces hello with something else.
- (IBAction)setContext:(id)sender {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [[NSBundle mainBundle] pathForResource:#"fullArray" ofType:#"plist"];
NSString *textFieldText = textField.text;
NSMutableDictionary *rootDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
[rootDict setValue:textField.text forKey:textField.text];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:#"fullArray.plist"];
[rootDict writeToFile:writablePath atomically: YES];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:#"fullArray.plist"]; //3
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
NSArray *array = [dictionary allKeys];
arrayContext = [[NSMutableArray alloc] initWithArray:array];
[pickerView selectRow:0 inComponent:0 animated:YES];
[textField endEditing:YES];
[pickerView reloadAllComponents];
}
How can I fix this?
Ok, you are creating a new NSMutableDictionary every time you pick something in the picker, the correct approach is:
Create a NSMutableDictionary as a property.
Every time you pick, create a new string for the key, maybe using [NSString stringWithFormat:].
use [mutableDictionary setObject:forKey] for set a new object in the mutant dictionary, with the new created key.