Separating a string? - iphone

- (IBAction)doUpload:(id)sender {
NSMutableString *str = [[NSMutableString alloc] initWithString:#"Selected: "];
for(int i = 0; i < [appDelegate.notesArray count]; i++) {
// UPLOAD STRINGS HERE
if(selected[i]) {
[str appendFormat:#"%# ", [appDelegate.notesArray objectAtIndex:i]];
}
}
UploadView *uploadview = (UploadView *)self.view;
if(uploadview != nil) {
[m_owner uploadString:str];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Selected Values" message:str delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
// [self dismissModalViewControllerAnimated:YES];
}
}
In the above code, the str variable contains some values from the tableview cell. My tableview has multiple selection enabled, so str contains multiple values.
This code:
[m_owner uploadString:str];
is used for uploading to gdoc, but when str contains multiple values, it uploads all the values at the same time. I want to separate the values, and then upload them one by one.
How can I do this?

NSString *str = #"Hi ! I am iPhone Developer";
NSArray *myWords = [str componentsSeparatedByString:#"!"];
NSString *str1 = [NSString stringWithFormat:#"%#",[myWords objectAtIndex:0]];
NSString *str2 = [NSString stringWithFormat:#"%#",[myWords objectAtIndex:1]];
NSLog(#"%#",str1);
NSLog(#"%#",str2);
You will find in Log like this
Hi
I am iPhone Developer

If you just want to separate the components you can try using the componentsSeperatedByString: method. As a result you will be getting an array of objects which you can use to iterate for uploading.
[yourString componentsSeparatedByString:separatorString];
hope this helps.

Related

International Chars in UIAlertView on iOS

I'm having trouble displaying international chars in UIAlertView.
I'm retrieving strings in JSON format from this URL.
The returned format is ok and it contains the correct characters.
When I try to load it in my app in an UIAlertView I see this:
What is the right way to display Unicode characters from Spanish, Croatian, Chinese, etc?
Changing the default language in the settings did not solve the problem.
Without any code, it's quite difficult to point out where you're going wrong. The code below works, I can only assume you're doing something particularly fruity with the encoded data.
NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://kancelarijahatipovic.com/translate.php?from=eng&dest=hr&phrase=iron"]] returningResponse:nil error:nil];
NSString *string = [NSString stringWithUTF8String:[data bytes]];
SBJsonParser *parser = [[SBJsonParser alloc] init];
id returnVal = [parser objectWithString:string];
if( [returnVal isKindOfClass:[NSDictionary class]]) {
//build string
NSMutableString *alertString = [NSMutableString string];
if( [returnVal objectForKey:#"tuc"] != nil ) {
NSArray *tucs = [returnVal objectForKey:#"tuc"];
for( id tucObject in tucs ) {
if( [tucObject isKindOfClass:[NSDictionary class]] && [tucObject objectForKey:#"phrase"] != nil ) {
id phraseObject = [tucObject objectForKey:#"phrase"];
if( [phraseObject isKindOfClass:[NSDictionary class]] && [phraseObject objectForKey:#"text"] != nil ) {
[alertString appendFormat:#"%#\n", [phraseObject objectForKey:#"text"]];
}
}
}
}
if( alertString.length > 0 ) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"example" message:alertString delegate:nil cancelButtonTitle:#"okay" otherButtonTitles: nil];
[alertView show];
}
}
Edit: the SBJsonParser objectWithData: provides the same result as above.

Display NSMutableArray in UIlabel in xcode

I have to display NSmutableArray data in UIlabel .But only the last index text is getting added .Here is my code
marray:
(
{
ID=1;
}
{
ID="2"
}
)
for(int i=0;i<[marray count];i++)
{
eventName=[[arr2 objectAtIndex:i]objectForKey:#"Code"];
label.text=[NSString stringWithFormat:#"ID :%#",eventName ];
}
I have to display these ID's in UIlabel with text as : 1 , 2
How can I do it?
you can append string to NSString object than use that object in label like bellow
NSMutableString *lblstr=#"ID :";
for (int i=0; i<[marray count]; i++) {
eventName=[[arr2 objectAtIndex:i]objectForKey:#"Code"];
[lblstr appendString:[NSString stringWithFormat:#"%#",eventName ]];
}
label.text=lblstr;
You are running a for loop which will continue executing till its last increment . So the last value in the array would be displayed. So what you can do is that you can add a timer instead of a for loop that is if you want to show your NSmutableArray as changing in the UILabel.
EDIT:
-(IBAction) rotate3
{
NSString *number = [self.dayArray description];
NSArray *array = [[NSArray alloc] initWithObjects: #"0", #"1", #"2", #"3", #"4", #"5" ,#"6", #"7", #"8",#"9",#"10",#"11",#"12",#"13", #"14", #"15", #"16", #"17", #"18", #"19",nil];
numberCount++;
timer=[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(rotate3 )userInfo:nil repeats:YES];
self.dayArray = array;
[array release];
label.text = [NSString stringWithFormat:#"Day %# ", number];
}
Also check these links How to update UILabel programmatically in iOS and How to display an NSArray in a UILabel and use timer
Try the below Code.
NSString *temp=#"";
for(int i=0;i<[marray count];i++)
{
//eventName=[[arr2 objectAtIndex:i]objectForKey:#"Code"];
temp=[temp stringByAppendingString:[[arr2 objectAtIndex:i]objectForKey:#"Code"]];
temp=[temp stringByAppendingString:#" ,"];
}
temp = [temp substringToIndex:[temp length]-1];
label.text=[NSString stringWithFormat:#"ID :%#",temp ];
NSMutableString *str = [[NSMutableString alloc] init];
for(int i=0;i<[marray count];i++)
{
NSString *temp = [NSString stringWithFormat:#"%d - %#\n",i+1, [[arr2 objectAtIndex:i]objectForKey:#"Code"]];
[str appendString:[NSString stringWithFormat:#"%#",temp]];
//sleep(0.05); //Remove comment this line may help ! **Tricky Line**
}
label.text = str;
[str release];
You may create an array of objects (indexes) and use componentsJoinedByString:
NSString* str = [array componentsJoindeByString: #", "];
Or using your code, replacing
label.text=[NSString stringWithFormat:#"ID :%#",eventName ];
with:
label.text=[label.text stringByAppendingFormat:#", %#", eventName];

how to separate a string from xml in ios

i have a note which can share it to evernote,i done it sucessfully.but there is an option called import note.when we tap the import button the notes fromn the evernote has to load in the importpage textview.but my problewm is the note from the evernote appers in xml formate with the note.my code for uploding note to evernote server is
-(IBAction)sendNoteEvernote:(id)sender{
EDAMNote * note = [[[EDAMNote alloc] init]autorelease];
// Setting initial values sent by the user
note.title = #"mybibleapp";
NSMutableString *str = [[NSMutableString alloc] initWithString:#"NOTES:"];
for (int i = 0; i<[appDelegate.notesArray count]; i++) {
NSString * aString = [[NSString alloc] initWithString:[appDelegate.notesArray objectAtIndex:i]] ;
NSString * ENML= [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n<en-note>%#",aString];
//aString contains the note value
ENML = [NSString stringWithFormat:#"%#%#", ENML, #"</en-note>"];
NSLog(#"%#", ENML);
// Adding the content & resources to the note
[note setContent:ENML];
#try {
[[Evernote sharedInstance] createNote:note];
_acteverbackup.hidden = YES;
_actimageeverbackup.hidden =YES;
}
#catch (EDAMUserException * e) {
_acteverbackup.hidden = YES;
_actimageeverbackup.hidden =YES;
NSString * errorMessage = [NSString stringWithFormat:#"Error saving note: error code %i", [e errorCode]];
proAlertView *alert = [[proAlertView alloc]initWithTitle:#"Evernote" message:errorMessage delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0] withStrokeColor:[UIColor colorWithHue:0.0 saturation:0.0 brightness:0.0 alpha:1.0]];
[alert show];
[alert release];
return;
}
i get the note in the everrnote correctly
this is my download or import code
- (void)viewDidLoad
{
[super viewDidLoad];
// Load the EDAMNote object that has guid we have stored in the object
EDAMNote * note = [(Evernote *)[Evernote sharedInstance] getNote:guid];
noteNavigation.topItem.title = [note title];
noteContent.text = [note content];
//noteContent is the textview which display the note
// Adding a back button to close the windows
UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(goBack:)];
UINavigationItem *item = [[[UINavigationItem alloc] init] autorelease];
item.leftBarButtonItem = doneButton;
item.hidesBackButton = YES;
[noteNavigation pushNavigationItem:item animated:NO];
noteNavigation.topItem.title = [note title];
}
noteContent is the textview which display the note ,here am getting this values
<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n<en-note>%#",mynote is here</en-note>
i need only mynote is here in this textview. How can I separate this from note?
There's a very nice NSString category that you can use, it's a part of the project MWFeedParser. More specifically, you look for the file NSString+HTML.
The NSString+HTML category now supports XML decoding, you can read about it here.
…NSString+XMLEntities category depreciated and replaced by NSString+HTML with improved HTML character entity encoding/decoding via Google Toolbox for Mac.
This category adds to following methods to the NSString class
- (NSString *)stringByStrippingTags;
- (NSString *)stringWithNewLinesAsBRs;
- (NSString *)stringByRemovingNewLinesAndWhitespace;
- (NSString *)stringByDecodingHTMLEntities;
- (NSString *)stringByEncodingHTMLEntities;
You should be able to transform XML into an NSString in a smart way by using it.
NSString *summary = [[[item.summary stringByStrippingTags] stringByRemovingNewLinesAndWhitespace] stringByDecodingHTMLEntities];
Hope it helps!

UITextField not saving text

I have a view with several UITextFields in it. I also have a high level UISegmentController that changes the view. When I enter text in a field, then press the hide keyboard button, then change segemnents, it saves fine. But when I enter text, and don't press the release keyboard button, then switch segments, it does not save the text.
How can I fix this?
Here is some of the code for the UITextField in my custom UITableViewCell:
- (IBAction)col2_doubleValueChanged:(id)sender
{
NSString *newValue = [NSString stringWithFormat:#"%#/%#", self.col2_doubleEntryValue_1.text, self.col2_doubleEntryValue_2.text];
NSMutableDictionary *result = [[[NSMutableDictionary alloc] init] autorelease];
[result setValue:self.row_key forKey:#"row_key"];
[result setValue:#"1" forKey:#"column"];
[result setValue:newValue forKey:#"col2_value"];
[[self delegate] editDidFinish:result];
[[self delegate] valueChanged];
}
- (IBAction)col2_singleValueEditDidBegin:(id)sender
{
}
Edit:
- (void)valueChanged
{
self.dirtyFlag = 1;
}
- (int)saveDataToServer
{
[self.tableView resignFirstResponder];
if (!dirtyFlag) {
return 0;
}
NSString *errors = [DataSource updatePatientWorkflowClinicalChecklistForAppointment:[[[DrChronoDataSource getCurrentAppointment] valueForKey:#"appointment_id"] intValue] clinicalInfo:self.clinicalChecklist checklistId:[self.clinicalChecklistId intValue] patientWorkflowServerId:patientWorkflowServerId];
if ((NULL == errors) || ![errors isEqualToString: #""]) {
//Show error messages.
if (NULL == errors) {
errors = #"Failed to save data to server. Please retry.";
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Status" message:errors delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return -1;
} else {
[self dismissModalViewControllerAnimated:FALSE];
}
self.dirtyFlag = 0;
return 0;
}
You do not have any writing functions.
- (IBAction)col2_doubleValueChanged:(id)sender
{
NSString *newValue = [NSString stringWithFormat:#"%#/%#", self.col2_doubleEntryValue_1.text, self.col2_doubleEntryValue_2.text];
NSMutableDictionary *result = [[[NSMutableDictionary alloc] init] autorelease];
[result setValue:self.row_key forKey:#"row_key"];
[result setValue:#"1" forKey:#"column"];
[result setValue:newValue forKey:#"col2_value"];
/* your aren't writing the new data anywhere,
you need to add something like this:
*/
[result writeToFile: #"somefile.txt" atomically: YES];
[[self delegate] editDidFinish:result];
[[self delegate] valueChanged];
}
Couldn't you link both events to the same action? Maybe you could make a BOOL in your header file called needsSaving. Set it to NO every time editing begins, then YES every time the data is saved successfully. Then only execute the body of your saving methods if needsSaving is NO, that will avoid unnecessary saving. I think doing this would simplify this function of your app. i.e.
- (IBAction)col2_singleValueEditDidBegin:(id)sender {
needsSaving = YES;
}
- (int)saveDataToServer
{
[self.tableView resignFirstResponder];
if (!dirtyFlag || !needsSaving) {
return 0;
}
NSString *errors = [DataSource updatePatientWorkflowClinicalChecklistForAppointment:[[[DrChronoDataSource getCurrentAppointment] valueForKey:#"appointment_id"] intValue] clinicalInfo:self.clinicalChecklist checklistId:[self.clinicalChecklistId intValue] patientWorkflowServerId:patientWorkflowServerId];
if ((NULL == errors) || ![errors isEqualToString: #""]) {
//Show error messages.
if (NULL == errors) {
errors = #"Failed to save data to server. Please retry.";
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Status" message:errors delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return -1;
} else {
needsSaving = NO;
[self dismissModalViewControllerAnimated:FALSE];
}
self.dirtyFlag = 0;
return 0;
}
Looks to me like you are not implementing the UITextFieldDelegate prototocols.

How to pase a JSON array in iphone sdk?

I have a login form where the user can login only with the valid memberID and password. If the user enter correct enamel and password i get a result string contains the user information that the user created in the signup process, if it the password is wrong it shows the status 400 as the result string, the result string is the json array which contains one f the above values, one thing is the if the success login occur it gives the staus 200 along with the user information, my need is to retrieve the status message from the array and i need to validate it within the app, if the login success(status 200) it needs to be redirected to the main page; if it is(status 400) it shows a unsuccessful login message.
my code:
EDit
-(IBAction)_clicksbtnsignIN:(id) sender
{
[_txtmemberId resignFirstResponder];
[_txtpassword resignFirstResponder];
NSString *connectionstring = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"]];
if ([connectionstring length]==0) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"you are not connected to the internet" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *emailString = _txtmemberId.text; // storing the entered email in a string.
// Regular expression to checl the email format.
NSString *emailReg = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailReg];
//[pool drain];
if (_txtmemberId.text.length == 0 || _txtpassword.text.length == 0) {
UIAlertView *alertblnk = [[UIAlertView alloc]initWithTitle:#"ALERT" message:#"Fill the required text fields" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alertblnk show];
[alertblnk release];
}
if (([emailTest evaluateWithObject:emailString] != YES) || [emailString isEqualToString:#""])
{
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Alert" message:#"Invalid Email ID" delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
}
else {
[_spinner startAnimating];
NSString *uname = _txtmemberId.text;
NSString *pwd = _txtpassword.text;
NSString *urlVal = #"http://dev.eltouchapps.net/api/?app=1&type=m1&action=t2&var1=";
NSString *urlVal1 = [urlVal stringByAppendingString:uname];
NSString *urlVal2 = [urlVal1 stringByAppendingString:#"&var2="];
NSString *urlVal3 = [urlVal2 stringByAppendingString:pwd];
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)urlVal3,NULL, (CFStringRef)#"\n" "",kCFStringEncodingUTF8 );
NSURL *url = [NSURL URLWithString:encodedString];
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Message" message:resultString delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
lblresult.text = resultString;
NSString *responseString = [resultString responseString];
NSLog(#"Got Profile: %#", responseString);
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
ParallelReadViewController *detailViewController = [[ParallelReadViewController alloc] initWithNibName:#"ParallelReadViewController" bundle:nil];
//detailViewController.firstString = firstString;
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
}
}
}
Result string is why i get from the server. I know there is parsing of JSONB array we want , but i didn't know how to done this.
Thanks in advance.
based on assumption of your response , try below code
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSMutableDictionary *responseJSON = (NSMutableDictionary *)[responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
Hope it gives you an idea.
Check out this JSON framework: https://github.com/stig/json-framework/