How to display NSArray objects in the buttons of a UIActionSheet - iphone

I'm trying to populate a UIActionSheet button list with the result from an NSArray. I have cityTitleNodeArray which is an NSArray (nslog output below). At the moment it only displays the first item in the NSArray as the first button in the UIActionSheet
I would like it to look like this (except the array info should all come from cityTitleNodeArray) :
NSArray *array = [[NSArray alloc] initWithObjects: cityTitleNodeArray, #"city2", #"city3", #"city4", #"city5", #"city6", #"city7", #"city8",#"city9", #"city10", #"city11", #"city12", #"city13", #"city14", #"city15", #"city16", nil];
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:#"Title Here"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
for (NSString *title in array) {
[actionSheet addButtonWithTitle:title];
}
[actionSheet addButtonWithTitle:#"Cancel"];
actionSheet.cancelButtonIndex = [array count];
[actionSheet showInView:self.view];
-(void)requestCityData {
NSError *requestError = nil;
NSString *savedValue = [[NSUserDefaults standardUserDefaults] stringForKey:#"token"];
NSString *stringWithToken = [NSString stringWithFormat:#"%#&token=%#",kCityURL, savedValue];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringWithToken]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&requestError];
NSError *jsonParsingError = nil;
if (requestError) {
NSLog(#"sync. request failed with error: %#", requestError);
}
else {
// handle data
NSDictionary *publicData = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
publicCityDataArray = [publicData objectForKey:#"data"];
for (NSDictionary *publicCityDataDict in publicCityDataArray) {
cityTitleNodeArray = [publicCityDataDict objectForKey:#"name"];
NSLog(#"cityTitleNodeArray from requestCityData output is %#",cityTitleNodeArray);
}
}
}
the cityTitleNodeArray output is:
`cityTitleNodeArray` from `requestCityData` output is Roma
2013-09-16 12:49:28.001 1000 [3980:907] cityTitleNodeArray from requestCityData output is Milano
2013-09-16 12:49:28.002 1000 [3980:907] cityTitleNodeArray from requestCityData output is Rimini
2013-09-16 12:49:28.002 1000 [3980:907] cityTitleNodeArray from requestCityData output is Venezia
2013-09-16 12:49:28.003 1000 [3980:907] cityTitleNodeArray from requestCityData output is Firenze
2013-09-16 12:49:28.003 1000 [3980:907] cityTitleNodeArray from requestCityData output is Napoli

NSArray *array = [[NSArray alloc] initWithObjects:
#"1st Button",
#"2nd Button",
#"3rd Button",
#"4th Button",
nil];
UIActionSheet* actionSheet = [[UIActionSheet alloc] init];
actionSheet.title = #"Cities Name";
actionSheet.delegate = self;
for(int i=0;i<[array count];i++)
{
[actionSheet addButtonWithTitle:[array objectAtIndex:i]];
}
actionSheet.cancelButtonIndex = [actionSheet addButtonWithTitle:#"Cancel"];
[actionSheet showInView:[UIApplication sharedApplication].keyWindow];

For Setting Title of Buttons From the array
UIActionSheet *actionSheet=[[UIActionSheet alloc]initWithTitle:#"Title" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:[array objectAtIndex:0],[array objectAtIndex:1],[array objectAtIndex:2], nil];
[actionSheet showInView:self.view];
In the delegate Method
pragma mark Action Sheet Delegate method
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
switch (buttonIndex) {
case 0:
{
//Actions on pressing Button 1
}
break;
case 1:
{
//Actions on pressing Button 2
}
break;
case 2:
{
//Actions on pressing Button 3
}
break;
default:
break;
}
}

Try this
NSArray *array = [[NSArray alloc] initWithObjects:
[NSString stringWithString:#"1st Button"],
[NSString stringWithString:#"2nd Button"],
[NSString stringWithString:#"3rd Button"],
[NSString stringWithString:#"4th Button"],
nil];
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:#"Title Here"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
// ObjC Fast Enumeration
for (NSString *title in array) {
[actionSheet addButtonWithTitle:title];
}
[actionSheet addButtonWithTitle:#"Cancel"];
actionSheet.cancelButtonIndex = [array count];
[actionSheet showInView:self.view];

Related

Using ARC and UITableViewController is throwing Observation info was leaked, and may even become mistakenly attached to some other object

I cannot seem to figure out what to do to resolve this error that I am receiving. I click on a cell which pops a new UITableViewController onto the stack. Once I hit the back button on the Navigation UI when in this controller I receive this error in the debugger but there doesn't seem to be any issue with the app as it doesn't crash or hang and still works fine.
An instance 0x79a8400 of class UITableView was deallocated while key value observers were still registered with it. Observation info was leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger. Here's the current observation info:
(
Context: 0x0, Property: 0x738c010>
)
Code is below and I am using similar code on other UITableViewControllers but not receiving the error.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
pull = [[PullToRefreshView alloc] initWithScrollView:(UIScrollView *) self.tableView];
[pull setDelegate:self];
[self.tableView addSubview:pull];
[tableView.dataSource self];
[tableView.delegate self];
NSString *isAuthenticated = [[NSString alloc] init];
isAuthenticated = [self retrieveUserToken:[[NSUserDefaults standardUserDefaults] valueForKey:#"email"]];
NSNumber *categorySelected = [[NSNumber alloc] init];
categorySelected = [[NSUserDefaults standardUserDefaults] valueForKey:#"category_id"];
if (![isAuthenticated length])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Message" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}else if (categorySelected ==nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"message" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}
[self getTableViewData];
}
- (void)viewDidUnload
{
[self setTableView:nil];
pull = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSString *)retrieveUserToken:(NSString *)user
{
NSError *error = nil;
NSString *username = user;
return [SFHFKeychainUtils getPasswordForUsername:username andServiceName:#"app" error:&error];
}
- (void)getTableViewData
{
URLSingleton *urls = [[URLSingleton alloc] init];
responseData = [NSMutableData data];
NSNumber *categoryID = [[NSNumber alloc] init];
categoryID = [[NSUserDefaults standardUserDefaults] valueForKey:#"category_id"];
NSString *urlComplete = [[NSString alloc] init];
urlComplete = [urls getEvent:categoryID];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlComplete]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[connection start];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return categories.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"cell"];
cell.textLabel.textColor = [UIColor blackColor];
cell.textLabel.text = [categories objectAtIndex:indexPath.row];
return cell;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.tableView reloadData];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Message." delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[pull finishedLoading];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *dictionary = [responseString JSONValue];
NSArray *response = [dictionary valueForKey:#"name"];
NSArray *responseID = [dictionary valueForKey:#"id"];
categories = [[NSMutableArray alloc] initWithArray:response];
eventID = [[NSMutableArray alloc] initWithArray:responseID];
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[pull finishedLoading];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [self.tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
int i = 0;
for(NSString *name in categories)
{
if ([name isEqualToString:cellText])
{
[[NSUserDefaults standardUserDefaults] setValue:[eventID objectAtIndex:i] forKey:#"event_id"];
[[NSUserDefaults standardUserDefaults] setValue:cellText forKey:#"event_name"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
i++;
}
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
if(checkedIndexPath) {
UITableViewCell* uncheckCell = [self.tableView
cellForRowAtIndexPath:checkedIndexPath];
uncheckCell.accessoryType = UITableViewCellAccessoryNone;
}
UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
checkedIndexPath = indexPath;
}
-(void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
URLSingleton *urls = [URLSingleton sharedInstance];
NSNumber *event = [[NSNumber alloc] init];
if(editingStyle == UITableViewCellEditingStyleDelete)
{
UITableViewCell *selectedCell = [self.tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
int i = 0;
for(NSString *name in categories)
{
if ([name isEqualToString:cellText])
{
event = [eventID objectAtIndex:i];
[eventID removeObjectAtIndex:i];
}
i++;
}
NSString *reqURL = [[NSString alloc] initWithString:[urls deleteEvent:[event stringValue]]];
NSURLRequest *delReq = [NSURLRequest requestWithURL:[NSURL URLWithString:reqURL]];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:delReq returningResponse: &resp error: &err];
NSString *reply = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
SBJsonParser *parser = [SBJsonParser new];
id content = [reply JSONValue];
if(!content){
NSLog(#"%#", parser.errorTrace);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
return;
}
NSNumber *status = [content valueForKey:#"success"];
NSNumber *one = [[NSNumber alloc] initWithInt:1];
if ([status isEqualToNumber:one])
{
[categories removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Message" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
}
}
}
- (void)pullToRefreshViewShouldRefresh:(PullToRefreshView *)view;
{
NSString *isAuthenticated = [[NSString alloc] init];
isAuthenticated = [self retrieveUserToken:[[NSUserDefaults standardUserDefaults] valueForKey:#"email"]];
NSNumber *categorySelected = [[NSNumber alloc] init];
categorySelected = [[NSUserDefaults standardUserDefaults] valueForKey:#"category_id"];
if (![isAuthenticated length])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Message" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}else if (categorySelected ==nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Message" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}
[self getTableViewData];
}
- (IBAction)createEvent:(id)sender
{
NSString *isAuthenticated = [[NSString alloc] init];
isAuthenticated = [self retrieveUserToken:[[NSUserDefaults standardUserDefaults] valueForKey:#"email"]];
NSNumber *categorySelected = [[NSNumber alloc] init];
categorySelected = [[NSUserDefaults standardUserDefaults] valueForKey:#"category_id"];
if (![isAuthenticated length])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Message" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}else if (categorySelected == nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Alert" delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil, nil];
[alert show];
return;
}
AddEventViewController *aevc = [self.storyboard instantiateViewControllerWithIdentifier:#"AddEventViewController"];
[self.navigationController popToViewController:aevc animated:YES];
}
I fixed it by adding the following method
- (void)dealloc
{
[self.tableView removeObserver:pull forKeyPath:#"contentOffset"];
}

dismissModalViewControllerAnimated not working as expected

I am trying to dismiss my view but for some reason when calling [self dismissModalViewControllerAnimated:NO]; nothing happens.
Options *option = [Options getInstance];
if(option.authToken != nil)
{
}
else
{
loginViewController = [[LoginViewController alloc] init];
[loginViewController setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
[self presentModalViewController:loginViewController animated:NO];
}
Then in my login view controller after logging in
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *theXML = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>%#",[[NSString alloc] initWithBytes: [responseData mutableBytes] length:[responseData length] encoding:NSUTF8StringEncoding]];
[self handleXmlResponse:theXML];
TBXML *tbXml = [[TBXML tbxmlWithXMLString:theXML] retain];
if(tbXml)
{
TBXMLElement *isError = [TBXML childElementNamed:#"IsError" parentElement:tbXml.rootXMLElement];
if([[TBXML textForElement:isError] isEqualToString:#"true"])
{
TBXMLElement *error = [TBXML childElementNamed:#"Error" parentElement:tbXml.rootXMLElement];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Login Error"
message:[TBXML textForElement:error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
TBXMLElement *value = [TBXML childElementNamed:#"Value" parentElement:tbXml.rootXMLElement];
Options* option = [Options getInstance];
option.authToken = [TBXML textForElement:value];
NSLog(#"YES");
[self dismissModalViewControllerAnimated:NO];
}
}
}
I have searched every where and can't figure out why this is happening
dismissModalViewControllerAnimated not working
Try Use dismissViewControllerAnimated:completion: instead.

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/

Saving buttonIndex into object(NSNumber)

I am trying to save the selectedIndex of actionsheet into an object. But why does it always read 0?
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
NSNumber *type, *count;
if ([actionSheet.title isEqualToString:#"Select Taxi Type"]) {
if (buttonIndex !=3) {
type = [NSNumber numberWithInteger:buttonIndex];
UIActionSheet *taxiCountQuery = [[UIActionSheet alloc] initWithTitle:#"Select Taxi Count" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"1", #"2", #"3", nil];
taxiCountQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
taxiCountQuery.tag = actionSheet.tag;
[taxiCountQuery showFromTabBar:self.tabBarController.tabBar];
[taxiCountQuery release];
}
}
else if ([actionSheet.title isEqualToString:#"Select Taxi Count"]){
if (buttonIndex !=3) {
NSLog(#"buttonIndex:%i", buttonIndex);
count = [NSNumber numberWithInteger:buttonIndex];
NSLog(#"type:%f", type); // always read 0
NSLog(#"count:%f", count); // always read 0
}
}
}
EDIT - 2nd part
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
NSNumber *type = [[NSNumber alloc] init];
if ([actionSheet.title isEqualToString:#"Select Taxi Type"]) {
if (buttonIndex !=3) {
type = [NSNumber numberWithInteger:buttonIndex];
UIActionSheet *taxiCountQuery = [[UIActionSheet alloc] initWithTitle:#"Select Taxi Count" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"1", #"2", #"3", nil];
taxiCountQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
taxiCountQuery.tag = actionSheet.tag;
[taxiCountQuery showFromTabBar:self.tabBarController.tabBar];
[taxiCountQuery release];
}
}
else if ([actionSheet.title isEqualToString:#"Select Taxi Count"]){
if (buttonIndex !=3) {
NSNumber *count = [[NSNumber alloc] initWithInteger:buttonIndex+1];
NSLog(#"buttonIndex:%i", buttonIndex);
count = [NSNumber numberWithInteger:buttonIndex +1];
NSLog(#"type:%i", [type intValue]); // always read 0
NSLog(#"count:%i", [count intValue]); // reads fine now
[count release];
}
}
}
NSNumber is an object that can hold basic types for storing in data structures like NSDictionary and NSArray. The %f in the NSLog is looking for a double.
This code should be giving you a warning.
If you do NSLog(#"%i",[type intValue]) you will get the right answer.
Please check out this code.
NSNumber *numberNs = [[NSNumber alloc] initWithInteger:buttonIndex];
Hope this helps you.

Sending Email in background in iphone sdk with body

I am developing on app in that i want to send email at the back ground.
for that i used the "SKPSMTP" library but when i got the mail it is without body so can any one tell me where i m wrong in my code.
following is the code on button click..
- (void)sendMessageInBack:(id)anObject
{
if(![self validateEmail:txt_email.text])
{
if([txt_email.text isEqualToString:#""] )
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Mandatory field" message:#"Please fill complete email" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
if(self.interfaceOrientation==UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation==UIInterfaceOrientationLandscapeRight )
{
if(rotate)
[btn_Send setImage:[UIImage imageNamed:#"send_button.png"] forState:UIControlStateNormal];
}
else if(self.interfaceOrientation==UIInterfaceOrientationPortrait || self.interfaceOrientation==UIInterfaceOrientationPortraitUpsideDown )
{
if(rotate)
[btn_Send setImage:[UIImage imageNamed:#"send button1.png"] forState:UIControlStateNormal];
}
NSLog(#"Start Sending");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"RequestReview.txt"];
NSData *dataObj = [NSData dataWithContentsOfFile:writableDBPath];
//NSString *mailid;
SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
testMsg.fromEmail =#"spymekdemo#gmail.com";
testMsg.toEmail = #"priyanka.chinchmalatpure#gmail.com";// txtEmail.text;
testMsg.relayHost = #"smtp.gmail.com";
testMsg.requiresAuth = YES;
testMsg.login = #"spymekdemo#gmail.com";
testMsg.pass =#"spymek123";
testMsg.subject =#"Sbject"; //[NSString stringWithFormat:#"Reply to Review From %#", txtName.text];
testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!
// Only do this for self-signed certs!
testMsg.validateSSLChain = NO;
testMsg.delegate = self;
NSString *deviceIdentifier=[NSString stringWithFormat:#"%#",[[UIDevice currentDevice]uniqueIdentifier]];//[NSString stringWithFormat:#"%#",deviceToken.uniqueIdentifier];
NSLog(#"%#",deviceIdentifier);
//NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
// [NSString stringWithFormat:#"Request Review\n\nDevice Identifier=%#\nProduct Name=%#\nProduct Download URL=%#\nUser Name=%#\nEmail=%#\nPromo Code=%#\nDescription Of Product=%#\n\n\n", deviceIdentifier, txtProduct.text,txtDownloadURL.text, txtName.text,txtEmail.text,txtPromocode.text, txtDescription.text]
// ,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/html",kSKPSMTPPartContentTypeKey,
[NSString stringWithFormat:#"<h2>Request Review</h2><br/><br/><b>Thank you for giving us your review</b> <br/>Device Identifier=%#<br/>Product Name=<br/>Product Download URL=<br/>User Name=<br/>Email=<br/>Promo Code=<br/>Description Of Product=<br/><br/><br/>", deviceIdentifier]
,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
// [NSString stringWithFormat:#"<h3>Review App</h3> <br/> <br/><b>Name=%#<b><br/> <br/>,\n<u>Email=%#</u><br/> <br/>,\nPassword=%#,<br/><br/> <b>\nComments=%#\n\n</b><br/>",txtName.text,txtMailId.text, txtPassword.text, txtComment.text],kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
// #"<html><body><h1>Review App</h1> <br/> <b>Some text to include in body</b></body></html>"
NSDictionary *vcfPart = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:#"text/directory;\r\n\tx-unix-mode=0644;\r\n\tname=\"%#.txt\"",txt_name.text],kSKPSMTPPartContentTypeKey,
[NSString stringWithFormat:#"attachment;\r\n\tfilename=\"%#.txt\"",txt_name.text],kSKPSMTPPartContentDispositionKey,[dataObj encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArray arrayWithObjects:plainPart,vcfPart, nil]; //vcfPart
[testMsg send];
}
}
rotate=YES;
}
- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
[message release];
//open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Unable to send email"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
//[self ClearFile];
//UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Request Review" message:#"Review Posting failed.. Try Again Later.." delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Done",nil];
}
- (void)messageSent:(SKPSMTPMessage *)message
{
[message release];
NSLog(#"delegate - message sent");
}