I erased the code between the lines, because it's nothing special, just adding a contact to an array. I think it has to do with the brackets. So hopefully someone has a good eye and can tell me, why its always adding a contact two times :)
if ([string rangeOfString:#"00"].location == NSNotFound) {
if(lastName && ([lastName length] > 0)) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(1, [str length] - 1)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=%#", ccode, Nummer, firstName, lastName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
else {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(1, [str length] - 1)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=""", ccode, Nummer, firstName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
} else if(lastName && ([lastName length] > 0)) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(0, [str length] - 0)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=%#", ccode, Nummer, firstName, lastName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
else {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(0, [str length] - 0)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=""", ccode, Nummer, firstName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
if ([string rangeOfString:#"+"].location == NSNotFound) {
if(lastName && ([lastName length] > 0)) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(1, [str length] - 1)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=%#", ccode, Nummer, firstName, lastName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
else {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(1, [str length] - 1)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=""", ccode, Nummer, firstName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
} else if(lastName && ([lastName length] > 0)) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(3, [str length] - 3)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=%#", ccode, Nummer, firstName, lastName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
else {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *ccode = [prefs stringForKey:#"cc"];
NSString *fileName = [prefs stringForKey:#"onumber"];
NSString *str = number;
NSString *newNumber = [str substringWithRange:NSMakeRange(3, [str length] - 3)];
NSString *Nummer = [newNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *strURL = [NSString stringWithFormat:#"http://myserver/phpFile.php?number=%#%#&name=%#&lastname=""", ccode, Nummer, firstName];
NSString *webStringURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
}
if ([string rangeOfString:#"+"].location == NSNotFound) condition should start with else.
It should be as below:
else if ([string rangeOfString:#"+"].location == NSNotFound)
Also, before the second if line (mentioned below)
if ([string rangeOfString:#"+"].location == NSNotFound))
you should have closed '}' for first if.
If some of the omitted code is executing twice, it's because the construction of your strings is such that two of your if statements are both true for the same string. Examine your strings, post the one that is being added twice. Does one of them have a + and 00 in it? But your bracketing is fine.
UPDATE
I guess I would start hunting this down by adding NSLog() statements to each of the if/else blocks to see when each is called. If you have a remote web service, the error could be there as well. In fact, it might be -- your obj-c code looks ok to me. Track GET requests at the server and add logging to phpFile.php.
Related
I have added a folder name Resources and under it there is another folder name File inside the file folder there are two xml files which i'm trying to parse. When i give pathforResource method name to my Resources folder it shows path is null. How can i access the two xml file from these folders?
Resources->File->text.xml.
My code is this,
NSMutableArray *aryXMLName = [NSMutableArray new];
[aryXMLName addObject:#"text.xml"];
[aryXMLName addObject:#"test1.xml"];
for(NSString *str in aryXMLName){
NSString *path = [[NSBundle mainBundle] pathForResource:str ofType:#"Resources"];
NSLog(#"Path : %#",path);
NSData *data=[NSData dataWithContentsOfFile:path];
if ([str isEqualToString:#"text.xml"]) {
if (data == nil)
return;
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"string: %#", str);
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLString:str];
NSLog(#"dictionary: %#", xmlDoc);
}else if ([str isEqualToString:#"test1.xml"]){
if (data == nil)
return;
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"string: %#", str);
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLString:str];
NSLog(#"dictionary: %#", xmlDoc);
}
}
The scenario is like this,
enter image description here
Replace this code:
NSMutableArray *aryXMLName = [NSMutableArray new];
[aryXMLName addObject:#"test"];
[aryXMLName addObject:#"text1"];
for(NSString *str in aryXMLName){
NSString *path = [[NSBundle mainBundle] pathForResource:str ofType:#"xml"];
NSLog(#"Path : %#",path);
NSData *data=[NSData dataWithContentsOfFile:path];
if ([str isEqualToString:#"test"]) {
if (data == nil)
return;
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"string: %#", str);
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLString:str];
NSLog(#"dictionary: %#", xmlDoc);
}else if ([str isEqualToString:#"text1"]){
if (data == nil)
return;
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"string: %#", str);
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLString:str];
NSLog(#"dictionary: %#", xmlDoc);
}
}
How can I convert a NSUUID to NSString?
NSString *url = [self mysql_process:ESTIMOTE_PROXIMITY_UUID];
- (NSString*)mysql_process:(NSUUID *)beacon_id
{
NSString *strURL = [NSString stringWithFormat:#"http://path_to_php_file/mysql.php?id=%#", beacon_id];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
return strResult;
}
When I try to NSLog the URL im getting a pointer, which shows me my NSUUID, ESTIMOTE_PROXIMITY_UUID in this case.
NSUUID has a method: -(NSString*)UUIDString;.
So:
NSString *uuidString = [yourNSUUID UUIDString]
swift 3 version
Ex:
let uuidStringValue = "12345678-1111-2222-3333-4567891012B4"
let proximityUUID = NSUUID(uuidString: uuidStringValue)
If you want NSString from NSUUID. Use UUIDString of NSUUID...
NSUUID *uuidStringRef = [[UIDevice currentDevice] identifierForVendor];
NSString *stringRef = [uuidStringRef UUIDString];//you can replace uuidStringRef with your ESTIMOTE_PROXIMITY_UUID
Hope it helps you...!
NSString *url = [self mysql_process:ESTIMOTE_PROXIMITY_UUID];
- (NSString*)mysql_process:(NSUUID *)beacon_id {
**NSString *strDeviceUUID = [beacon_id UUIDString];** // Converts NSUUID to UUIDString format
NSLog(#"beacon_id : %# strDeviceUUID : %# ", beacon_id,strDeviceUUID);
NSString *strURL = [NSString stringWithFormat:#"http://path_to_php_file/mysql.php?id=%#", strDeviceUUID];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
return strResult;
}
This function is present in NSUUID.h file of Foundation frameworks.
/* Return a string description of the UUID, such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" */
- (NSString *) UUIDString;
I have a text file that I download at launch from my website. It saves it to the Documents directory in the app. I want to read and process that text file and turn it into an NSArray.
I tried this:
- (NSArray *)articleReason {
NSString *filename3 = #"GameList.txt";
NSArray *pathArray3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory3 = [pathArray3 objectAtIndex:0];
NSString *yourSoundPath3 = [documentsDirectory3 stringByAppendingPathComponent:filename3];
NSURL *url = [NSURL fileURLWithPath:yourSoundPath3 isDirectory:NO];
NSString *urlData = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSArray *parsed = [urlData componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSIndexSet *indexes = [parsed indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
NSRange range = [(NSString *)obj rangeOfString:#"Reason:"];
if (range.location != NSNotFound)
{
return YES;
}
return NO;
}];
NSArray *disallowed = [parsed objectsAtIndexes:indexes];
NSString * myString = [disallowed componentsJoinedByString:#" "];
disallowed = [myString componentsSeparatedByString:#"Reason: "];
return disallowed;
}
This does not work. The thing is, if I download the text file while making the NSArray, it ends up working. Here's that code:
- (NSArray *)articleReason {
NSString *stringURL = kGameURL;
NSURL *url = [NSURL URLWithString:stringURL];
NSString *urlData = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSArray *parsed = [urlData componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSIndexSet *indexes = [parsed indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
NSRange range = [(NSString *)obj rangeOfString:#"Reason:"];
if (range.location != NSNotFound)
{
return YES;
}
return NO;
}];
NSArray *disallowed = [parsed objectsAtIndexes:indexes];
NSString * myString = [disallowed componentsJoinedByString:#" "];
disallowed = [myString componentsSeparatedByString:#"Reason: "];
return disallowed;
}
Any idea why this is not working? I verified in the Documents directory that the text file is downloading correctly. I do the downloading of the file in didFinishLaunching in the App Delegate. Here's that code:
NSString *stringURL2 = kGameURL;
NSURL *url2 = [NSURL URLWithString:stringURL2];
NSString *urlData2 = [NSString stringWithContentsOfURL:url2 encoding:NSUTF8StringEncoding error:nil];
NSFileManager *fileManager2 = [NSFileManager defaultManager];
NSString *docsDirectory2 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path2 = [docsDirectory2 stringByAppendingPathComponent:#"GameList.txt"];
[urlData2 writeToFile:path2 atomically:YES ];
Any help would be greatly appreciated.
Figured it out.
[urlData2 writeToFile:path2 atomically:YES ];
Writeto file needed it include the encoding.
can some pne please help me in optimize this code:
- (NSMutableDictionary *) parseResponse:(NSData *) data {
NSString *myData = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"JSON data = %#", myData);
NSError *jsonParsingError = nil;
//parsing the JSON response
id jsonObject = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&jsonParsingError];
if (jsonObject != nil && jsonParsingError == nil)
{
//NSLog(#"Successfully deserialized...");
NSLog(#"json object is %#",jsonObject);
if([jsonObject isKindOfClass:[NSDictionary class]])
{
NSLog(#"It has only dictionary so simply read it");
}
else if([jsonObject isKindOfClass:[NSArray class]])
{
NSLog(#"It has only NSArray so simply read it");
}
else if([jsonObject isKindOfClass:[NSString class]])
{
NSString *stringWithoutOpenCurly = [jsonObject stringByReplacingOccurrencesOfString:#"{" withString:#""];
NSString *stringWithoutOpenAndCloseCurly = [stringWithoutOpenCurly stringByReplacingOccurrencesOfString:#"}" withString:#""];
NSArray *arrayOfKeyValue = [stringWithoutOpenAndCloseCurly componentsSeparatedByString:#","];
NSString *statusString = [arrayOfKeyValue objectAtIndex:0];
NSArray *statusKeyValueArray = [statusString componentsSeparatedByString:#":"];
NSString *statusKey, *statusValue;
statusKey = [[statusKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
statusValue = [[statusKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *messageString = [arrayOfKeyValue objectAtIndex:1];
NSArray *messageKeyValueArray = [messageString componentsSeparatedByString:#":"];
NSString *messageKey, *messageValue;
messageKey = [[messageKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
messageValue = [[messageKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *dataIdString = [arrayOfKeyValue objectAtIndex:2];
NSArray *dataIdKeyValueArray = [dataIdString componentsSeparatedByString:#":"];
NSString *dataIdKey, *dataIdValue;
dataIdKey = [[dataIdKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
dataIdValue = [[dataIdKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *nextString = [arrayOfKeyValue objectAtIndex:3];
NSArray *nextKeyValueArray = [nextString componentsSeparatedByString:#":"];
NSString *nextKey, *nextValue;
nextKey = [[nextKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
nextValue = [[nextKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *b64String = [arrayOfKeyValue objectAtIndex:4];
NSArray *b64KeyValueArray = [b64String componentsSeparatedByString:#":"];
NSString *b64Key, *b64Value;
b64Key = [[b64KeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
b64Value = [[b64KeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *fileNameString = [arrayOfKeyValue objectAtIndex:5];
NSArray *fileNameKeyValueArray = [fileNameString componentsSeparatedByString:#":"];
NSString *fileNameKey, *fileNameValue;
fileNameKey = [[fileNameKeyValueArray objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
fileNameValue = [[fileNameKeyValueArray objectAtIndex:1] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSMutableDictionary *responseDictionary = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:statusValue, messageValue, dataIdValue, nextValue, b64Value, fileNameValue, nil] forKeys:[NSArray arrayWithObjects:statusKey, messageKey, dataIdKey, nextKey, b64Key, fileNameKey, nil]];
NSLog(#"manually created dictionary is ++++++++++++++++++++++++++++++%#",responseDictionary);
NSLog(#"statusValue is ++++++++++++++++++++++++++++++%#",[responseDictionary valueForKey:statusKey]);
return responseDictionary;
}
}
else //previoucly no else handler so put it here
{
// mErrorMessage = #"Server Error";
// [self stopIndicatorProgressWithError];
}
}
jsonObject is true for NSString class only???? do not know what's problem.
Any Help?
thanks & regards.
You can "optimize" your code by using the appropriate Foundation classes:
NSString *jsonObject = ...; // your JSON data as string
NSData *jsonData = [jsonObject dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary * responseDictionary = [NSJSONSerialization JSONObjectWithData:jsonData
options:0 error:&error];
or, if you really need a mutable dictionary:
NSMutableDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers error:&error];
I am sending URLRequest as mentioned below.
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *balanceString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
And I am getting #"23.0984 USD" in balanceString
Then I would like to display it on uilabel.tex= 23.09 USD Please help me
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *balanceString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
float amount = [balanceString floatValue]; // This will return 23.0984 as a float
NSString *formattedAmount = [NSString stringWithFormat:#"%01.2f USD", amount];
Then something like this should work:
NSString * inp = #"29.2994 USD";
// Initialize a scanner to process the input
NSScanner * scanner = [NSScanner scannerWithString:inp];
// Pull out a floating point value
float v;
[scanner scanFloat:&v];
NSCharacterSet * ws = [NSCharacterSet whitespaceAndNewlineCharacterSet];
// scan through the whitespace after the float
[scanner scanCharactersFromSet:ws intoString:nil];
NSString * currency;
[scanner scanUpToCharactersFromSet:ws intoString:¤cy];
// write out value:
uilabel.text= [NSString stringWithFormat:#"%.2f %#",v,currency];
There might be easier ways.. But this should work..
NSString *originalString = #"23.0984 USD";
NSString *numberString = [originalString stringByReplacingOccurrencesOfString:#" USD"
withString:#""];
float number = [numberString floatValue];
NSString *changedString = [NSString stringWithFormat:#"%.2f",number];
NSLog(#"ChangedString : %# USD",changedString);
EDIT: This answer is already accepted. But I think a better method to get number from string is to search for spaces rather than replacing hardcoded string #" USD".
NSString *originalString = #"23.0984 USD";
NSString *numberString = nil;
NSArray *parts = [originalString componentsSeparatedByString:#" "]; //space
if(parts && [parts lenght]){
numberString = [parts objectAtIndex:0];
}
float number = [numberString floatValue];
NSString *changedString = [NSString stringWithFormat:#"%.2f",number];
NSLog(#"ChangedString : %# USD",changedString);