Search Results

Search found 605 results on 25 pages for 'stringwithformat'.

Page 4/25 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • -[NSConcreteMutableData release]: message sent to deallocated instance

    - by kamibutt
    Dear members, I am facing a problem of -[NSConcreteMutableData release]: message sent to deallocated instance, i have attached my sample code as well. - (IBAction)uploadImage { NSString *urlString = @"http://192.168.1.108/iphoneimages/uploadfile.php?userid=1&charid=23&msgid=3"; //if(FALSE) for (int i=0; i<[imgArray count]; i++) { // setting up the request object now NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; /* add some header info now we always need a boundary when we post a file also we need to set the content type You might want to generate a random boundary.. this is just the same as my output from wireshark on a valid html post */ NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"]; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; /* now lets create the body of the post */ NSMutableData *body = [[NSMutableData data] autorelease]; NSString *str = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"ipodfile%d.jpg\"\r\n",i]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:str] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; NSData *imageData = UIImageJPEGRepresentation([imgArray objectAtIndex:i], 90); [body appendData:[NSData dataWithData:imageData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; // setting the body of the post to the reqeust [request setHTTPBody:body]; // now lets make the connection to the web [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; //NSLog(@"%@",returnString); [imageData release]; [request release]; //[body release]; } } It successfully upload the images to the folder and there is no any error in the execution but when it complete it process and try to go back it give error -[NSConcreteMutableData release]: message sent to deallocated instance Please help me out. Thanks

    Read the article

  • iPhone: Can access files in documents directory in Simulator, but not device

    - by Kevin Cupp
    Hi there! I'm writing an app that copies some contents of the bundle into the applications Document's directory, mainly images and media. I then access this media throughout the app from the Document's directory. This works totally fine in the Simulator, but not on the device. The assets just come up as null. I've done NSLog's and the paths to the files look correct, and I've confirmed that the files exist in the directory by dumping a file listing in the console. Any ideas? Thank you! EDIT Here's the code that copies to the Document's directory NSString *pathToPublicationDirectory = [NSString stringWithFormat:@"install/%d",[[[manifest objectAtIndex:i] valueForKey:@"publicationID"] intValue]]; NSString *manifestPath = [[NSBundle mainBundle] pathForResource:@"content" ofType:@"xml" inDirectory:pathToPublicationDirectory]; [self parsePublicationAt:manifestPath]; // Get actual bundle path to publication folder NSString *bundlePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:pathToPublicationDirectory]; // Then build the destination path NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", [[[manifest objectAtIndex:i] valueForKey:@"publicationID"] intValue]]]; NSError *error = nil; // If it already exists in the documents directory, delete it if ([fileManager fileExistsAtPath:destinationPath]) { [fileManager removeItemAtPath:destinationPath error:&error]; } // Copy publication folder to documents directory [fileManager copyItemAtPath:bundlePath toPath:destinationPath error:&error]; I am figuring out the path to the docs directory with this method: - (NSString *)applicationDocumentsDirectory { return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; } And here's an example of how I'm building a path to an image path = [NSString stringWithFormat:@"%@/%d/%@", [self applicationDocumentsDirectory], [[thisItem valueForKey:@"publicationID"] intValue], [thisItem valueForKey:@"coverImage"]];

    Read the article

  • Problem with reusing UITableViewCell's

    - by Sheehan Alam
    I have a UITableView that is re-using cells when the user scrolls. Everything appears and scrolls fine, except when the user clicks on an actual row, the highlighted cell displays some text from another cell. I'm not exactly sure why. #define IMAGE_TAG 1111 #define LOGIN_TAG 2222 #define FULL_NAME_TAG 3333 // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; STUser *mySTUser = [[[STUser alloc]init]autorelease]; mySTUser = [items objectAtIndex:indexPath.row]; AsyncImageView* asyncImage = nil; UILabel* loginLabel = nil; UILabel* fullNameLabel = nil; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; } else { asyncImage = (AsyncImageView *) [cell.contentView viewWithTag:IMAGE_TAG]; loginLabel = (UILabel *) [cell.contentView viewWithTag:LOGIN_TAG]; fullNameLabel = (UILabel *) [cell.contentView viewWithTag:FULL_NAME_TAG]; } // Configure the cell... cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; CGRect frame = CGRectMake(0, 0, 44, 44); asyncImage = [[[AsyncImageView alloc]initWithFrame:frame] autorelease]; asyncImage.tag = IMAGE_TAG; NSURL* url = [NSURL URLWithString:mySTUser.avatar_url_large]; [asyncImage loadImageFromURL:url]; [cell.contentView addSubview:asyncImage]; loginLabel.tag = LOGIN_TAG; CGRect loginLabelFrame = CGRectMake(60, 0, 200, 10); loginLabel = [[[UILabel alloc] initWithFrame:loginLabelFrame] autorelease]; loginLabel.text = [NSString stringWithFormat:@"%@",mySTUser.login]; [cell.contentView addSubview:loginLabel]; fullNameLabel.tag = FULL_NAME_TAG; CGRect fullNameLabelFrame = CGRectMake(60, 20, 200, 10); fullNameLabel = [[[UILabel alloc] initWithFrame:fullNameLabelFrame] autorelease]; fullNameLabel.text = [NSString stringWithFormat:@"%@ %@",mySTUser.first_name, mySTUser.last_name]; //[NSString stringWithFormat:@"%@",mySTUser.login]; [cell.contentView addSubview:fullNameLabel]; return cell; }

    Read the article

  • dialing on iphone/ipod touch not working with documented procedures

    - by dave
    I'm trying to set up an iphone app to the phone number of a various sports store using the tel:// url passing method- I am developing on an ipod touch- usually on the touch you see the error message "Unsupported URL - This URL wasn't loaded tel://99887766" when you try and dial a number. I cant get this message to appear on the simulator or the ipod touch. do I need to do some sort of fancy signing before the app will dial properly? I am using this code: [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", [selectedBar phoneNumber]]]]; and I've tried adding the slashes: [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", [selectedBar phoneNumber]]]]; but neither work. I have also tried this way: [[UIApplication application] openURL:[NSURL URLWithString:@"tel://99887766"]]; and this way: NSMutableString *phone = [[@"+ 12 34 567 89 01" mutableCopy] autorelease]; [phone replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [phone length])]; [phone replaceOccurrencesOfString:@"(" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [phone length])]; [phone replaceOccurrencesOfString:@")" withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [phone length])]; NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", phone]]; [[UIApplication sharedApplication] openURL:url]; No matter what i do i can't get any response from the simulator / ipod touch that it is dealing with a phone number- When I press the button associated with this code, it doesnt crash, it's like its processed it and decided not to do anything. i even put an NSLog(@"button called"); in just before the code to confirm the button was working, which it is.

    Read the article

  • Problem in encoding and decoding the string in Iphone sdk

    - by monish
    HI Guys, Here I am having a problem In encoding/decoding the strings. Actually I had a string which I am encoding it using the base64.which was working fine. And now I need to decode the string that was encoded before and want to print it. I code I written as: I imported the base64.h and base64.m files into my application which contains the methods as: + (NSData *) dataWithBase64EncodedString:(NSString *) string; - (id) initWithBase64EncodedString:(NSString *) string; - (NSString *) base64EncodingWithLineLength:(unsigned int) lineLength; And the code in my view controller where I encode the String is: - (id)init { if (self = [super init]) { // Custom initialization userName = @"Sekhar"; password = @"Bethalam"; } return self; } -(void)reloadView { NSString *authStr = [NSString stringWithFormat:@"%@:%@",userName,password]; NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding]; NSString *authValue = [NSString stringWithFormat:@"%@", [authData base64EncodingWithLineLength:30]]; NSLog(authValue); //const char *str = authValue; //NSString *decStr = [StringEncryption DecryptString:authValue]; //NSLog(decStr); //NSData *decodeData = [NSData decode:authValue]; //NSString *decStr = [NSString stringWithFormat:@"%@",decodeData]; //NSStr //NSLog(decStr); } -(void)viewWillAppear:(BOOL)animated { [self reloadView]; } and now I want to decode the String that I encoded. But I dont know How to do that.can anyone suggest me with code how to get it. Anyone's help will be much appreciated. Thank you, Monish.

    Read the article

  • NSMutableArray Problem - iPhone

    - by David Schiefer
    Hi, I'm trying to get a UITableView to read it's data from a file. I've attempted it like this: NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *fullFileName = [NSString stringWithFormat:@"%@/entries.plist", documentsDirectory]; self.dataForTable = [[NSMutableArray alloc] initWithContentsOfFile:fullFileName]; This compiles fine, but when saving something to the file in the following snippet, the file is not saved nor anything is written to the array: NSMutableDictionary*userDictionary; userDictionary = [[NSMutableDictionary alloc] init]; [userDictionary setObject:name.text forKey:@"name"]; [userDictionary setObject:email.text forKey:@"email"]; [userDictionary setObject:serial.text forKey:@"serial"]; [userDictionary setObject:notes.text forKey:@"notes"]; [userDictionary setObject:[NSNumber numberWithInt:[licenseType selectedRowInComponent:0]] forKey:@"license_type"]; [userDictionary setObject:[date date] forKey:@"date"]; [userDictionary setObject:[NSNumber numberWithBool:[paymentSwitch isOn]] forKey:@"payment"]; NSString*dirToSaveTo = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; NSString*fileName = [NSString stringWithFormat:@"%@.plist",name.text]; NSString*saveName = [dirToSaveTo stringByAppendingPathComponent:fileName]; [userDictionary writeToFile:saveName atomically:NO]; NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *fullFileName = [NSString stringWithFormat:@"%@/entries.plist", documentsDirectory]; [self.dataForTable addObject:name.text]; NSLog(@"%@",self.dataForTable); [self.dataForTable writeToFile:fullFileName atomically:YES]; The NSLog just returns (null). The *plist file is never written. What am I doing wrong?

    Read the article

  • iPhone SDK math - pythagorean theorem problem!

    - by Flafla2
    Just as a practice, I am working on an app that solves the famous middle school pythagorean theorem, a squared + b squared = c squared. Unfortunately, the out-coming answer has, in my eyes, nothing to do with the actual answer. Here is the code used during the "solve" action. - (IBAction)solve { int legoneint; int legtwoint; int hypotenuseint; int lonesq = legoneint * legoneint; int ltwosq = legtwoint * legtwoint; int hyposq = hypotenuseint * hypotenuseint; hyposq = lonesq + ltwosq; if ([legone.text isEqual:@""]) { legtwoint = [legtwo.text intValue]; hypotenuseint = [hypotenuse.text intValue]; answer.text = [NSString stringWithFormat:@"%d", legoneint]; self.view.backgroundColor = [UIColor blackColor]; } if ([legtwo.text isEqual:@""]) { legoneint = [legone.text intValue]; hypotenuseint = [hypotenuse.text intValue]; answer.text = [NSString stringWithFormat:@"%d", legtwoint]; self.view.backgroundColor = [UIColor blackColor]; } if ([hypotenuse.text isEqual:@""]) { legoneint = [legone.text intValue]; legtwoint = [legtwo.text intValue]; answer.text = [NSString stringWithFormat:@"%d", hypotenuseint]; self.view.backgroundColor = [UIColor blackColor]; } } By the way, legone, legtwo, and hypotenuse all represent the UITextField that corresponds to each mathematical part of the right triangle. Answer is the UILabel that tells, you guessed it, the answer. Does anyone see any flaws in the program? Thanks in advance!

    Read the article

  • a + sing in email address

    - by d.andreykiv
    Hi. I need to submit an email address with a "+" sign and validate in on server. But server receives email like "[email protected]" as "aaa [email protected]". I send all data as POST request with following code NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", url, @"/signUp"]]; NSString *post = [NSString stringWithFormat:@"&email=%@&userName=%@&password=%@", user.email, user.userName, user.password]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO]; NSData* data = [self sendRequest:url postData:postData]; post variable before encoding has value &[email protected]&userName=Asdfasdfadsfadsf&password=sdfasdf after encoding it is same &[email protected]&userName=Asdfasdfadsfadsf&password=sdfasdf Method I use to send request looks like following code: -(id) sendRequest:(NSURL*) url postData:(NSData*)postData { // Create request NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; [request setURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:postData]; NSURLResponse *urlResponse; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil]; [request release]; return data; }

    Read the article

  • Find Exact difference between two dates

    - by iPhone Fun
    Hi all , I want some changes in the date comparison. In my application I am comparing two dates and getting difference as number of Days, but if there is only one day difference the system shows me 0 as a difference of days. I do use following code NSDateFormatter *date_formater=[[NSDateFormatter alloc]init]; [date_formater setDateFormat:@"MMM dd,YYYY"]; NSString *now=[NSString stringWithFormat:@"%@",[date_formater stringFromDate:[NSDate date]]]; LblTodayDate.text = [NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@",now]]; NSDate *dateofevent = [[NSUserDefaults standardUserDefaults] valueForKey:@"CeremonyDate_"]; NSDate *endDate =dateofevent; NSDate *startDate = [NSDate date]; gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; unsigned int unitFlags = NSDayCalendarUnit; NSDateComponents *components = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0]; int days = [components day]; I found some solutions that If we make the time as 00:00:00 for comparision then it will show me proper answer , I am right or wrong i don't know. Please help me to solve the issue

    Read the article

  • Creating Actions from UIActionSheets help

    - by user337174
    I am using two UIAction sheets within my current project. I can get one to work perfectly fine but when i insert a second action sheet it runs the same arguements as the first. How do i define the actionsheets seperatly? -(IBAction) phoneButtonClicked:(id)sender { // open a dialog with just an OK button UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:[NSString stringWithFormat:@"Phone: %@",phone],nil]; actionSheet.actionSheetStyle = UIActionSheetStyleDefault; [actionSheet showInView:self.view]; // show from our table view (pops up in the middle of the table) [actionSheet release]; } -(IBAction) mapButtonClicked:(id)sender { // open a dialog with just an OK button UIActionSheet *mapActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:[NSString stringWithFormat:@"Map"],nil]; mapActionSheet.actionSheetStyle = UIActionSheetStyleDefault; [mapActionSheet showInView:self.view]; // show from our table view (pops up in the middle of the table) [mapActionSheet release]; } -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { if(buttonIndex == 0){ NSString *callPhone = [NSString stringWithFormat:@"tel:%@",phone]; NSLog(@"Calling: %@", callPhone); [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]]; } }

    Read the article

  • UIWebview :: Text :: HTML :: JS

    - by user306089
    hello, 1- i load a text from a txt file 2- i show it into a html "file" 3- problem : 3-a : this code works : i create my page by code and i insert my text myText = ... loaded from an array of texts ...; NSString *myDescriptionHTML = [NSString stringWithFormat:@"<html> \n" "<head> \n" "<style type=\"text/css\"> \n" "body {font-family: \"%@\"; font-size: 1.0f + 'em'; color:#FFF;}\n" "</style> \n" "</head> \n" "<body id=\"myid\">%@</body> \n" "</html>", @"Arial", myText]; [self.myWebView loadHTMLString:myDescriptionHTML baseURL:nil]; 3-b but this one does not work : i load a html page already created and i inject my text into using JS : myText = ... loaded from an array of texts ...; [self.myWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById(\"myid\").innerHTML = \"%@\";", myText]]; 3-c but this one working : same as 3-b but i init my text with a string in the code itself : myText = @"hello all"; [self.myWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById(\"myid\").innerHTML = \"%@\";", myText]]; any help to understand what's wrong with 3-b ? thank you

    Read the article

  • Text being printed twice in uitableview

    - by user337174
    I have created a uitableview that calculates the distance of a location in the table. I used this code in cell for row at index path. NSString *lat1 = [object valueForKey:@"Lat"]; NSLog(@"Current Spot Latitude:%@",lat1); float lat2 = [lat1 floatValue]; NSLog(@"Current Spot Latitude Float:%g", lat2); NSString *long1 = [object valueForKey:@"Lon"]; NSLog(@"Current Spot Longitude:%@",long1); float long2 = [long1 floatValue]; NSLog(@"Current Spot Longitude Float:%g", long2); //Getting current location from NSDictionary CoreDataTestAppDelegate *appDelegate = (CoreDataTestAppDelegate *) [[UIApplication sharedApplication] delegate]; NSString *locLat = [NSString stringWithFormat:appDelegate.latitude]; float locLat2 = [locLat floatValue]; NSLog(@"Lat: %g",locLat2); NSString *locLong = [NSString stringWithFormat:appDelegate.longitude]; float locLong2 = [locLong floatValue]; NSLog(@"Long: %g",locLong2); //Location of selected spot CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:lat2 longitude:long2]; //Current Location CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:locLat2 longitude:locLong2]; double distance = [loc1 getDistanceFrom: loc2] / 1600; NSMutableString* converted = [NSMutableString stringWithFormat:@"%.1f", distance]; [converted appendString: @" m"]; It works fine apart from a problem i have just discovered where the distance text is duplicated over the top of the detailed text label when you scroll beyond the height of the page. here's a screen shot of what i mean. Any ideas why its doing this?

    Read the article

  • SLRequest return nil before block complete

    - by jaytr0n
    I'm having a little trouble thinking through this and deciding if it's a design flaw on my behalf or if I'm missing a piece that could make this work. Basically I'm using the new SLRequest to make a Twitter API call. After the data is returned, I'd like to put it into an object and return that object: -(AUDSlide *) getFollowerSlide { SLRequest *getRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:[NSURL URLWithString:[NSString stringWithFormat:@"https://api.twitter.com/1.1/followers/ids.json?user_id=%@", [[self.twitterAccount valueForKey:@"properties"] valueForKey:@"user_id"]]] parameters:nil]; getRequest.account = twitterAccount; AUDSlide *slide = [[AUDSlide alloc] init]; [getRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { if ([urlResponse statusCode] == 200) { NSError *jsonError = nil; NSDictionary *list = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonError]; NSLog(@"Number of Followers: %u", [[list objectForKey:@"ids"] count]); slide.title = @"Followers"; slide.number = [NSString stringWithFormat:@"%u",[[list objectForKey:@"ids"] count]]; } else{ slide.title = @"Error"; slide.number = [NSString stringWithFormat: @"E%u", [urlResponse statusCode]]; } }]; return slide; } Of course the slide is returned before the call is complete and returns a nil object. So I'm not sure if I should try to force this into a synchronous request (that seems like it could be a bad idea) or rethink the design. Does anyone have any advice?

    Read the article

  • error “EXC_BAD_ACCESS” in my programm

    - by zp26
    Hi, i have a problem. When i compile my program there isn't a error but, when i start it these retern with “EXC_BAD_ACCESS”. I looking for the error with the debug and i find it in these method but i don't understand where... Can you help me? Thanks and sorry for the english. PS:the program enters in the loop sometimes. -(void)updateMinPosition{ float valueMinX = 150; float valueMinY = 150; float valueMinZ = 150; NSString *nameMinimoX = [NSString stringWithFormat:@"default"]; NSString *nameMinimoY = [NSString stringWithFormat:@"default"]; NSString *nameMinimoZ = [NSString stringWithFormat:@"default"]; for(int i = 0; i< [arrayPosizioniMovimento count]; i++){ //Posizione is my class. It contain a NSString name, 3 float valueX, valueY, valueZ Posizione *tempPosition; tempPosition = [[Posizione alloc]init]; tempPosition = [arrayPosizioniMovimento objectAtIndex:i]; if(tempPosition.valueX <= valueMinX){ valueMinX = tempPosition.valueX; nameMinimoX = tempPosition.nome; } if(tempPosition.valueY <= valueMinY){ valueMinY = tempPosition.valueY; nameMinimoY = tempPosition.nome; } if(tempPosition.valueZ <= valueMinZ){ valueMinZ = tempPosition.valueZ; nameMinimoZ = tempPosition.nome; } [tempPosition dealloc]; } labelMinX.text = nameMinimoX; labelMinY.text = nameMinimoY; labelMinZ.text = nameMinimoZ; }

    Read the article

  • TBXML parsing issue while the value cannot get in UILabel

    - by Dany
    In my app I'm using TBXML parser where I need to get a value from xml file and print it on the label. This is my xml file in server <gold> <price> <title>22 K Gold</title> </price> <price> <title>24 K Gold</title> </price> </gold> any my Viewcontroller.h looks like #import <UIKit/UIKit.h> #import "TBXML.h" @interface ViewController : UIViewController{ IBOutlet UILabel *lab; IBOutlet UILabel *lab1; TBXML *tbxml; } @end and my Viewcontrooler.m looks like - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSData *xmlData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://www.abcde.com/sample.xml"]]; tbxml = [[TBXML alloc]initWithXMLData:xmlData]; TBXMLElement * root = tbxml.rootXMLElement; if (root) { TBXMLElement * elem_PLANT = [TBXML childElementNamed:@"price" parentElement:root]; while (elem_PLANT !=nil) { TBXMLElement * elem_BOTANICAL = [TBXML childElementNamed:@"title" parentElement:elem_PLANT]; NSString *botanicalName = [TBXML textForElement:elem_BOTANICAL]; lab.text=[NSString stringWithFormat:@"re %@", botanicalName]; elem_PLANT = [TBXML nextSiblingNamed:@"price" searchFromElement:elem_PLANT]; elem_BOTANICAL = [TBXML childElementNamed:@"title" parentElement:elem_PLANT]; botanicalName = [TBXML textForElement:elem_BOTANICAL]; lab1.text=[NSString stringWithFormat:@"re %@", botanicalName]; } } } I'm getting BAD_ACCESS thread. Am I missing anything?

    Read the article

  • NSURLConnection request seems to disappear into thin air

    - by ibergmark
    Hi Everybody! I'm having trouble with a NSURLConnection request. My app calls a routine called sayHello to identify a user's device. This code works fine for all devices I've tested it on, but for some devices the request just seems to disappear into thin air with no errors or popups on the device. One specific device that fails is an iPod Touch 2G running OS 3.1.3. The app start's fine and doesn't crash, and none of my error popup messages are displayed. I just can't understand why my server never receives the request since the call to initWithRequest returns a pointer. Any help is much appreciated. Thanks. Here's the relevant header info: @interface Globals : NSObject { UserItem *userData; NSURLConnection *urlConnection; NSString *imageCacheLocation; NSOperationQueue *opQueue; } Here's the implementation of sayHello: - (void)sayHello:(BOOL)updateVisits; { NSString *updString; if (updateVisits) updString = @"Y"; else updString = @"N"; NSDictionary *dataDict = [[NSDictionary alloc] initWithObjectsAndKeys: [[UIDevice currentDevice] uniqueIdentifier], @"id", kProgVersion, @"pv", @"1", @"pr", userData.tagID, @"tg", updString, @"uv", nil]; NSString *urlString = [[NSString alloc] initWithString:kHelloURL]; urlConnection = [self localPOST:dataDict toUrl:urlString delegate:self]; [dataDict release]; [urlString release]; } - (NSURLConnection *)localPOST:(NSDictionary *)dictionary toUrl:(NSString *)urlString delegate:(id)delegate { NSString *myBounds = [[NSString alloc] initWithString:@"0xKmYbOuNdArY"]; NSMutableData *myPostData = [[NSMutableData alloc] initWithCapacity:10]; NSArray *formKeys = [dictionary allKeys]; for (int i = 0; i < [formKeys count]; i++) { [myPostData appendData:[[NSString stringWithFormat:@"--%@\n", myBounds] dataUsingEncoding:NSUTF8StringEncoding]]; [myPostData appendData:[[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"%@\"\n\n%@\n", [formKeys objectAtIndex:i], [dictionary valueForKey:[formKeys objectAtIndex:i]]] dataUsingEncoding:NSUTF8StringEncoding]]; } [myPostData appendData:[[NSString stringWithFormat:@"--%@--\n", myBounds] dataUsingEncoding:NSUTF8StringEncoding]]; NSURL *myURL = [[NSURL alloc] initWithString:urlString]; NSMutableURLRequest *myRequest = [[NSMutableURLRequest alloc] initWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30]; NSString *myContent = [[NSString alloc] initWithFormat: @"multipart/form-data; boundary=%@", myBounds]; [myRequest setValue:myContent forHTTPHeaderField:@"Content-Type"]; [myRequest setHTTPMethod:@"POST"]; [myRequest setHTTPBody:myPostData]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:delegate]; if (!connection) { [[Globals sharedGlobals] showAlertWithTitle: NSLocalizedString( @"Connection failed", @"alert title - connection failed") message: NSLocalizedString( @"Could not open a connection.", @"alert message - connection failed")]; } [myBounds release]; [myPostData release]; [myURL release]; [myRequest release]; [myContent release]; return connection; } - (void)handleNetworkError:(NSError *)error { if (networkErrorAlert) return; networkErrorAlert = YES; [[Globals sharedGlobals] showAlertWithTitle: NSLocalizedString( @"Network error", @"alert title - network error") message: [NSString stringWithFormat: NSLocalizedString( @"This app needs a network connection to function properly.", @"alert message - network error")] otherButtons:nil delegate:self]; } - (void) connectionDidFinishLoading:(NSURLConnection *)connection { [urlConnection release]; urlConnection = nil; } - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [self handleNetworkError:error]; [urlConnection release]; urlConnection = nil; }

    Read the article

  • iPhone NSCalendar - Incorrect Calendar Drawn for users outside US

    - by xoail
    After trying to work on someone else's code, and so many different iterations, I am unable to understand what am I doing wrong with dates on a calendar month view. I am trying to present a calendar in month view fashion like calendar.app but unfortunately some users in countries like Australia, UK are reporting incorrect alignment of Days to Dates. For instance in Australia it displays 17th March as Friday. Any help is highly appreciated! Here is the code sample I am using: -(void)setCalendar { NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *comps = [gregorian components:units fromDate:[NSDate date]]; self.currentDate = [gregorian dateFromComponents:comps]; NSInteger weekdayInteger=[comps weekday]; currentMonth=[comps month]; currentYear=[comps year]; NSString *dateString=[[NSString stringWithFormat:@"%@",currentDate] substringToIndex:10]; NSArray *array= [dateString componentsSeparatedByString:@"-"]; NSInteger currentDay=[[array objectAtIndex:2] intValue]; currentMonthConstant=currentMonth; currentYearConstant=currentYear; currentDayConstant=currentDay; currentConstantDate=[NSString stringWithFormat:@"%d/%d/%d",currentDayConstant,currentMonthConstant,currentYearConstant]; currentFirstDay=((8+weekdayInteger-(currentDay%7))%7); if(currentFirstDay==0) currentFirstDay=7; [gregorian release]; } And this is how im populating the calendar: -(void)fillCalender:(NSInteger)month weekStarts:(NSInteger)weekday year:(NSInteger)year { currentMonth=month; currentYear=year; currentFirstDay=weekday; UIButton *temp; NSInteger numberOfDays=[self getNumberofDays:month YearVlue:year]; currentLastDay=(currentFirstDay+numberOfDays-1)%7; if(currentLastDay==0) currentLastDay=7; NSString *monthName=[self getMonth:month]; NSInteger grid=(weekday-1); monthLabel.text=[NSString stringWithFormat:@"%@ %d",monthName,year]; for(int i=1;i<=numberOfDays;i++) { if([frontView isEqualToString:@"view1"]) temp=[arr_View2Buttons objectAtIndex:grid]; else temp= [arr_View1Buttons objectAtIndex:grid]; [temp setBackgroundImage:nil forState:UIControlStateNormal]; [temp setUserInteractionEnabled:TRUE]; UILabel *aLbl = (UILabel *)[temp viewWithTag:123]; [aLbl setText:[NSString stringWithFormat:@"%d",i]]; // check for today if(currentDayConstant == i && currentMonthConstant == currentMonth && currentYearConstant == currentYear) { [aLbl setTextColor:[UIColor blueColor]]; } else { [aLbl setTextColor:[UIColor colorWithRed:69/255.0 green:2/255.0 blue:71/255.0 alpha:1.0]]; } [temp setTag:i]; grid++; if(grid==35) grid=0; } } And finally viewdidload: - (void)viewDidLoad { [super viewDidLoad]; [self setCalendar]; // set views [self.view1 setFrame:CGRectMake(0,45,320,232)]; [self.view2 setFrame:CGRectMake(0,277,320,232)]; [self.view addSubview:self.view1]; [self.view addSubview:self.view2]; frontView = @"view2"; [self fillCalender:currentMonth weekStarts:currentFirstDay year:currentYear]; frontView = @"view1"; }

    Read the article

  • UITableview has problem reloading

    - by seelani
    Hi guys, I've kinda finished my application for a school project but have run into a major "bug". It's a account management application. I'm unable to insert a picture here so here's a link: http://i232.photobucket.com/albums/ee112/seelani/Screenshot2010-12-22atPM075512.png Here's the problem when i click on the plus sign, i push a nav controller to load another view to handle the adding and deleting of categories. When i add and return back to the view above, it doesn't update. It only updates after i hit the button on the right which is another view used to change some settings, and return back to the page. I did some research on viewWillAppear and such but I'm still confused to why it doesn't work properly. This problem is also affecting my program when i delete a category, and return back to this view it crashes cos the view has not reloaded successfully. I will get this error when deleting and returning to the view. "* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 4 beyond bounds [0 .. 3]'". [EDIT] Table View Code: @class LoginViewController; @implementation CategoryTableViewController @synthesize categoryTableViewController; @synthesize categoryArray; @synthesize accountsTableViewController; @synthesize editAccountTable; @synthesize window; CategoryMgmtTableController *categoryMgmtTableController; ChangePasswordView *changePasswordView; - (void) save_Clicked:(id)sender { /* UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Category Management" message:@"Load category management table view" delegate:self cancelButtonTitle: @"OK" otherButtonTitles:nil]; [alert show]; [alert release]; */ KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate]; categoryMgmtTableController = [[CategoryMgmtTableController alloc]initWithNibName:@"CategoryMgmtTable" bundle:nil]; [appDelegate.categoryNavController pushViewController:categoryMgmtTableController animated:YES]; } - (void) change_Clicked:(id)sender { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Change Password" message:@"Change password View" delegate:self cancelButtonTitle: @"OK" otherButtonTitles:nil]; [alert show]; [alert release]; KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate]; changePasswordView = [[ChangePasswordView alloc]initWithNibName:@"ChangePasswordView" bundle:nil]; [appDelegate.categoryNavController pushViewController:changePasswordView animated:YES]; /* KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate]; categoryMgmtTableController = [[CategoryMgmtTableController alloc]initWithNibName:@"CategoryMgmtTable" bundle:nil]; [appDelegate.categoryNavController pushViewController:categoryMgmtTableController animated:YES]; */ } #pragma mark - #pragma mark Initialization /* - (id)initWithStyle:(UITableViewStyle)style { // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. if ((self = [super initWithStyle:style])) { } return self; } */ -(void) initializeCategoryArray { sqlite3 *db= [KeyCryptAppAppDelegate getNewDBConnection]; KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate]; const char *sql = [[NSString stringWithFormat:(@"Select Category from Categories;")]cString]; const char *cmd = [[NSString stringWithFormat:@"pragma key = '%@' ", appDelegate.pragmaKey]cString]; sqlite3_stmt *compiledStatement; sqlite3_exec(db, cmd, NULL, NULL, NULL); if (sqlite3_prepare_v2(db, sql, -1, &compiledStatement, NULL)==SQLITE_OK) { while(sqlite3_step(compiledStatement) == SQLITE_ROW) [categoryArray addObject:[NSString stringWithUTF8String:(char*) sqlite3_column_text(compiledStatement, 0)]]; } else { NSAssert1(0,@"Error preparing statement", sqlite3_errmsg(db)); } sqlite3_finalize(compiledStatement); } #pragma mark - #pragma mark View lifecycle - (void)viewDidLoad { // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; [super viewDidLoad]; } - (void)viewWillAppear:(BOOL)animated { self.title = NSLocalizedString(@"Categories",@"Types of Categories"); categoryArray = [[NSMutableArray alloc]init]; [self initializeCategoryArray]; self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(save_Clicked:)] autorelease]; self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(change_Clicked:)] autorelease]; [super viewWillAppear:animated]; } - (void)viewDidAppear:(BOOL)animated { NSLog (@"view did appear"); [super viewDidAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { NSLog (@"view will disappear"); [super viewWillDisappear:animated]; } - (void)viewDidDisappear:(BOOL)animated { [categoryTableView reloadData]; NSLog (@"view did disappear"); [super viewDidDisappear:animated]; } /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ #pragma mark - #pragma mark Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [self.categoryArray count]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell... NSUInteger row = [indexPath row]; cell.text = [categoryArray objectAtIndex:row]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; return cell; } /* // Override to support conditional editing of the table view. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } */ /* // Override to support editing the table view. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { } */ /* // Override to support conditional rearranging of the table view. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the item to be re-orderable. return YES; } */ #pragma mark - #pragma mark Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSString *selectedCategory = [categoryArray objectAtIndex:[indexPath row]]; NSLog (@"AccountsTableView.xib is called."); if ([categoryArray containsObject: selectedCategory]) { if (self.accountsTableViewController == nil) { AccountsTableViewController *aAccountsView = [[AccountsTableViewController alloc]initWithNibName:@"AccountsTableView"bundle:nil]; self.accountsTableViewController =aAccountsView; [aAccountsView release]; } NSInteger row =[indexPath row]; accountsTableViewController.title = [NSString stringWithFormat:@"%@", [categoryArray objectAtIndex:row]]; // This portion pushes the categoryNavController. KeyCryptAppAppDelegate *delegate = [[UIApplication sharedApplication] delegate]; [self.accountsTableViewController initWithTextSelected:selectedCategory]; KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate]; appDelegate.pickedCategory = selectedCategory; [delegate.categoryNavController pushViewController:accountsTableViewController animated:YES]; } } #pragma mark - #pragma mark Memory management - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Relinquish ownership any cached data, images, etc that aren't in use. } - (void)viewDidUnload { // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. // For example: self.myOutlet = nil; } - (void)dealloc { [accountsTableViewController release]; [super dealloc]; } @end And the code that i used to delete rows(this is in a totally different tableview): - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source NSString *selectedCategory = [categoryArray objectAtIndex:indexPath.row]; [categoryArray removeObjectAtIndex:indexPath.row]; [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; [deleteCategoryTable reloadData]; //NSString *selectedCategory = [categoryArray objectAtIndex:indexPath.row]; sqlite3 *db= [KeyCryptAppAppDelegate getNewDBConnection]; KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate]; const char *sql = [[NSString stringWithFormat:@"Delete from Categories where Category = '%@';", selectedCategory]cString]; const char *cmd = [[NSString stringWithFormat:@"pragma key = '%@' ", appDelegate.pragmaKey]cString]; sqlite3_stmt *compiledStatement; sqlite3_exec(db, cmd, NULL, NULL, NULL); if (sqlite3_prepare_v2(db, sql, -1, &compiledStatement, NULL)==SQLITE_OK) { sqlite3_exec(db,sql,NULL,NULL,NULL); } else { NSAssert1(0,@"Error preparing statement", sqlite3_errmsg(db)); } sqlite3_finalize(compiledStatement); } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } }

    Read the article

  • iOS bluetooth low energy not detecting peripherals

    - by user3712524
    My app won't detect peripherals. Im using light blue to simulate a bluetooth low energy peripheral and my app just won't sense it. I even installed light blue on two devices to make sure it was generating a peripheral signal properly and it is. Any suggestions? My labels are updating and the NSLog is showing that the scanning is starting. Thanks in advance. #import <UIKit/UIKit.h> #import <CoreBluetooth/CoreBluetooth.h> @interface ViewController : UIViewController @property (weak, nonatomic) IBOutlet UITextField *navDestination; @end #import "ViewController.h" @implementation ViewController - (IBAction)connect:(id)sender { } - (IBAction)navDestination:(id)sender { NSString *destinationText = self.navDestination.text; } - (void)viewDidLoad { } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end #import <UIKit/UIKit.h> #import "ViewController.h" @interface BlueToothViewController : UIViewController @property (strong, nonatomic) CBCentralManager *centralManager; @property (strong, nonatomic) CBPeripheral *discoveredPerepheral; @property (strong, nonatomic) NSMutableData *data; @property (strong, nonatomic) IBOutlet UITextView *textview; @property (weak, nonatomic) IBOutlet UILabel *charLabel; @property (weak, nonatomic) IBOutlet UILabel *isConnected; @property (weak, nonatomic) IBOutlet UILabel *myPeripherals; @property (weak, nonatomic) IBOutlet UILabel *aLabel; - (void)centralManagerDidUpdateState:(CBCentralManager *)central; - (void)centralManger:(CBCentralManager *)central didDiscoverPeripheral: (CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; -(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error; -(void)cleanup; -(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral; -(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error; -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error; -(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error; -(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error; -(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error; @end @interface BlueToothViewController () @end @implementation BlueToothViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { _centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil options:nil]; _data = [[NSMutableData alloc]init]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [_centralManager stopScan]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)centralManagerDidUpdateState:(CBCentralManager *)central { //you should test all scenarios if (central.state == CBCentralManagerStateUnknown) { self.aLabel.text = @"I dont do anything because my state is unknown."; return; } if (central.state == CBCentralManagerStatePoweredOn) { //scan for devices [_centralManager scanForPeripheralsWithServices:nil options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : @YES }]; NSLog(@"Scanning Started"); } if (central.state == CBCentralManagerStateResetting) { self.aLabel.text = @"I dont do anything because my state is resetting."; return; } if (central.state == CBCentralManagerStateUnsupported) { self.aLabel.text = @"I dont do anything because my state is unsupported."; return; } if (central.state == CBCentralManagerStateUnauthorized) { self.aLabel.text = @"I dont do anything because my state is unauthorized."; return; } if (central.state == CBCentralManagerStatePoweredOff) { self.aLabel.text = @"I dont do anything because my state is powered off."; return; } } - (void)centralManger:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI { NSLog(@"Discovered %@ at %@", peripheral.name, RSSI); self.myPeripherals.text = [NSString stringWithFormat:@"%@%@",peripheral.name, RSSI]; if (_discoveredPerepheral != peripheral) { //save a copy of the peripheral _discoveredPerepheral = peripheral; //and connect NSLog(@"Connecting to peripheral %@", peripheral); [_centralManager connectPeripheral:peripheral options:nil]; self.aLabel.text = [NSString stringWithFormat:@"%@", peripheral]; } } -(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error { NSLog(@"Failed to connect"); [self cleanup]; } -(void)cleanup { //see if we are subscribed to a characteristic on the peripheral if (_discoveredPerepheral.services != nil) { for (CBService *service in _discoveredPerepheral.services) { if (service.characteristics != nil) { for (CBCharacteristic *characteristic in service.characteristics) { if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"508EFF8E-F541-57EF-BD82-B0B4EC504CA9"]]) { if (characteristic.isNotifying) { [_discoveredPerepheral setNotifyValue:NO forCharacteristic:characteristic]; return; } } } } } } [_centralManager cancelPeripheralConnection:_discoveredPerepheral]; } -(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { NSLog(@"Connected"); [_centralManager stopScan]; NSLog(@"Scanning stopped"); self.isConnected.text = [NSString stringWithFormat:@"Connected"]; [_data setLength:0]; peripheral.delegate = self; [peripheral discoverServices:nil]; } -(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error { if (error) { [self cleanup]; return; } for (CBService *service in peripheral.services) { [peripheral discoverCharacteristics:nil forService:service]; } //discover other characteristics } -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error { if (error) { [self cleanup]; return; } for (CBCharacteristic *characteristic in service.characteristics) { [peripheral setNotifyValue:YES forCharacteristic:characteristic]; } } -(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { if (error) { NSLog(@"Error"); return; } NSString *stringFromData = [[NSString alloc]initWithData:characteristic.value encoding:NSUTF8StringEncoding]; self.charLabel.text = [NSString stringWithFormat:@"%@", stringFromData]; //Have we got everything we need? if ([stringFromData isEqualToString:@"EOM"]) { [_textview setText:[[NSString alloc]initWithData:self.data encoding:NSUTF8StringEncoding]]; [peripheral setNotifyValue:NO forCharacteristic:characteristic]; [_centralManager cancelPeripheralConnection:peripheral]; } } -(void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { if ([characteristic.UUID isEqual:nil]) { return; } if (characteristic.isNotifying) { NSLog(@"Notification began on %@", characteristic); } else { [_centralManager cancelPeripheralConnection:peripheral]; } } -(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error { _discoveredPerepheral = nil; self.isConnected.text = [NSString stringWithFormat:@"Connecting..."]; [_centralManager scanForPeripheralsWithServices:nil options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : @YES}]; } @end

    Read the article

  • Using the PayPal API in an iPhone application

    - by jaynaiphone
    Hello I want to use Paypal in my iphone application, I have find the soapRequest to integrating the paypal API. My code is NSString *soapMessage = [NSString stringWithFormat: @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<SOAP-ENV:Envelope xmlns:xsi= \"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n" "<SOAP-ENV:Header>\n" "<RequesterCredentials xmlns=\"urn:ebay:api:PayPalAPI\">\n" "<Credentials xmlns=\"urn:ebay:apis:eBLBaseComponents\">\n" "<Username>api_username</Username>\n" "<Password>api_password</Password>\n" "<Signature/>\n" "<Subject/>\n" "</Credentials>\n" "</RequesterCredentials>\n" "</SOAP-ENV:Header>\n" "<SOAP-ENV:Body>\n" "<specific_api_name_Req xmlns=\"urn:ebay:api:PayPalAPI\">\n" "<specific_api_name_Request>\n" "<Version xmlns=urn:ebay:apis:eBLBaseComponents”>service_version</Version>\n" "<required_or_optional_fields xsi:type=”some_type_here”>\n" "</required_or_optional_fields>\n" "</specific_api_name_Request>\n" "</specific_api_name_Req>\n" "</SOAP-ENV:Body>\n" "</SOAP-ENV:Envelope>\n"]; NSLog(@"Soap message===%@",soapMessage); NSString *parameterString = [NSString stringWithFormat:@"USER=%@&PWD=%@&SIGNATURE=%@&VERSION=57.0&METHOD=SetMobileCheckout&AMT=%.2f&CURRENCYCODE=USD&DESC=%@&RETURNURL=%@", userName, password, signature, donationAmount, @"Some Charge", returnCallURL]; NSLog(parameterString); NSURL *url = [NSURL URLWithString:paypalUrlNVP]; NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url]; NSString *msgLength = [NSString stringWithFormat:@"%d", [parameterString length]]; [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"]; [theRequest setHTTPMethod:@"POST"]; [theRequest setHTTPBody: [parameterString dataUsingEncoding:NSUTF8StringEncoding]]; NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if( theConnection ){ webData = [[NSMutableData data] retain]; // [self displayConnectingView]; }else{ NSLog(@"theConnection is NULL"); } But here I am not getting the value of paypalUrlNVP. How can i get it?? And if possible then please give some example of paypalAPI integration in iphone. I also want to use checkout functionality.I am new in this field so I have no idea about it. So, kindly give me whole sample code. Thanks in advance.

    Read the article

  • tableView:didSelectRowAtIndexPath: calls TTNavigator openURLAction:applyAnimated: — UITabBar and na

    - by vikingosegundo
    I have an existing iphone project with a UITabBar. Now I need styled text and in-text links to other ViewControllers in my app. I am trying to integrate TTStyledTextLabel. I have a FirstViewController:UITabelViewController with this tableView:didSelectRowAtIndexPath: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSString *url; if ([self.filteredQuestions count]>0) { url = [NSString stringWithFormat:@"%@%d", @"tt://question/", [[self.filteredQuestions objectAtIndex:indexPath.row] id]]; [[TTNavigator navigator] openURLAction:[[TTURLAction actionWithURLPath: url] applyAnimated:YES]]; } else { Question * q = [self.questions objectAtIndex:indexPath.row] ; url = [NSString stringWithFormat:@"%@%d", @"tt://question/", [q.id intValue]]; } TTDPRINT(@"%@", url); TTNavigator *navigator = [TTNavigator navigator]; [navigator openURLAction:[[TTURLAction actionWithURLPath: url] applyAnimated:YES]]; } My mapping looks like this: TTNavigator* navigator = [TTNavigator navigator]; navigator.window = window; navigator.supportsShakeToReload = YES; TTURLMap* map = navigator.URLMap; [map from:@"*" toViewController:[TTWebController class]]; [map from:@"tt://question/(initWithQID:)" toViewController:[QuestionDetailViewController class]]; and my QuestionDetailViewController: @interface QuestionDetailViewController : UIViewController <UIScrollViewDelegate , QuestionDetailViewProtocol> { Question *question; } @property(nonatomic,retain) Question *question; -(id) initWithQID:(NSString *)qid; -(void) goBack:(id)sender; @end When I hit a cell, q QuestionDetailViewController will be called — but the navigationBar wont @implementation QuestionDetailViewController @synthesize question; -(id) initWithQID:(NSString *)qid { if (self = [super initWithNibName:@"QuestionDetailViewController" bundle:nil]) { //; TTDPRINT(@"%@", qid); NSManagedObjectContext *managedObjectContext = [(domainAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext]; NSPredicate *predicate =[NSPredicate predicateWithFormat:@"id == %@", qid]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Question" inManagedObjectContext:managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entity]; [request setPredicate:predicate]; NSError *error = nil; NSArray *array = [managedObjectContext executeFetchRequest:request error:&error]; if (error==nil && [array count]>0 ) { self.question = [array objectAtIndex:0]; } else { TTDPRINT(@"error: %@", array); } } return self; } - (void)viewDidLoad { [super viewDidLoad]; [TTStyleSheet setGlobalStyleSheet:[[[TextTestStyleSheet alloc] init] autorelease]]; [self.navigationController.navigationBar setTranslucent:YES]; NSArray *includedLinks = [self.question.answer.text vs_extractExternalLinks]; NSMutableDictionary *linksToTT = [[NSMutableDictionary alloc] init]; for (NSArray *a in includedLinks) { NSString *s = [a objectAtIndex:3]; if ([s hasPrefix:@"/answer/"] || [s hasPrefix:@"http://domain.com/answer/"] || [s hasPrefix:@"http://www.domain.com/answer/"]) { NSString *ttAdress = @"tt://question/"; NSArray *adressComps = [s pathComponents]; for (NSString *s in adressComps) { if ([s isEqualToString:@"qid"]) { ttAdress = [ttAdress stringByAppendingString:[adressComps objectAtIndex:[adressComps indexOfObject:s]+1]]; } } [linksToTT setObject:ttAdress forKey:s]; } } for (NSString *k in [linksToTT allKeys]) { self.question.answer.text = [self.question.answer.text stringByReplacingOccurrencesOfString:k withString: [linksToTT objectForKey:k]]; } TTStyledTextLabel *answerText = [[[TTStyledTextLabel alloc] initWithFrame:CGRectMake(0, 0, 320, 700)] autorelease]; if (![[self.question.answer.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] hasPrefix:@"<div"]) { self.question.answer.text = [NSString stringWithFormat:@"%<div>%@</div>", self.question.answer.text]; } NSString * s = [NSString stringWithFormat:@"<div class=\"header\">%@</div>\n%@",self.question.title ,self.question.answer.text]; answerText.text = [TTStyledText textFromXHTML:s lineBreaks:YES URLs:YES]; answerText.contentInset = UIEdgeInsetsMake(20, 15, 20, 15); [answerText sizeToFit]; [self.navigationController setNavigationBarHidden:NO animated:YES]; [self.view addSubview:answerText]; [(UIScrollView *)self.view setContentSize:answerText.frame.size]; self.view.backgroundColor = [UIColor whiteColor]; [linksToTT release]; } ....... @end This works quite nice, as soon as a cell is touched, a QuestionDetailViewController is called and pushed — but the tabBar will disappear, and the navigationItem — I set it like this: self.navigationItem.title =@"back to first screen"; — won't be shown. And it just appears without animation. But if I press a link inside the TTStyledTextLabel the animation works, the navigationItem will be shown. How can I make the animation, the navigationItem and the tabBar be shown?

    Read the article

  • TTLauncherItem: change badge immediately (or: how to refresh TTLauncherView)

    - by vikingosegundo
    I have a TTLauncherView with some TTLauncherItems. These show badges, representing messages from the network. I set the badges in viewWillAppear:, so if I switch to another view and then return, the correct badges are shown. But I want to update the badges as soon a message comes in. Calling setNeedsDisplay on TTLauncherView doesn't help? How can I refresh the TTLauncherView? in my MessageReceiver class I do this: TTNavigator* navigator = [TTNavigator navigator]; [(OverviewController *)[navigator viewControllerForURL:@"tt://launcher"] reloadLauncherView] ; My TTViewController-derived OverviewController @implementation OverviewController - (id)init { if (self = [super init]) { self.title = OverviewTitle; } return self; } - (void)dealloc { [items release]; [overView release]; [super dealloc]; } -(void)viewDidLoad { [super viewDidLoad]; overView = [[TTLauncherView alloc] initWithFrame:self.view.bounds]; overView.backgroundColor = [UIColor whiteColor]; overView.delegate = self; overView.columnCount = 4; items = [[NSMutableArray alloc] init]; for(int i = 1; i <= NumberOfBars; ++i){ NSString *barID = [NSString stringWithFormat:NameFormat, IDPrefix, i]; TTLauncherItem *item = [[[TTLauncherItem alloc] initWithTitle:barID image:LogoPath URL:[NSString stringWithFormat:@"tt://item/%d", i] canDelete:NO] autorelease]; [barItems addObject: item]; } overView.pages = [NSArray arrayWithObject:items]; [self.view addSubview:overView]; } -(void)viewWillAppear:(BOOL)animated { for(int i = 0; i <[barItems count]; i++){ TTLauncherItem *item = [items objectAtIndex:i]; NSString *barID = [NSString stringWithFormat:NameFormat, IDPrefix, i+1]; P1LOrderDispatcher *dispatcher = [OrderDispatcher sharedInstance]; P1LBarInbox *barInbox = [dispatcher.barInboxMap objectForKey:barID]; item.badgeNumber = [[barInbox ordersWithState:OrderState_New]count]; } [super viewWillAppear:animated]; } - (void)launcherView:(TTLauncherView*)launcher didSelectItem:(TTLauncherItem*)item { TTDPRINT(@"%@", item); TTNavigator *navigator = [TTNavigator navigator]; [navigator openURLAction:[TTURLAction actionWithURLPath:item.URL]]; } -(void)reloadLauncherView { [overView setNeedsDisplay];//This doesn't work } @end

    Read the article

  • String Formatting Tricks/Docs

    - by Meltemi
    Was reading the response by Shaggy Frog to this post and was intrigued by the following line of code: NSLog(@"%@", [NSString stringWithFormat:@"%@:%*s%5.2f", key, padding, " ", [object floatValue]]); I know string formatting is an age old art but I'm kinda doing the end around into Cocoa/Obj-C programming and skipped a few grades along the way. Where is a good (best) place to learn all the string formatting tricks allowed in NSString's stringWithFormat? I'm familiar with Apple's String Format Specifiers page but from what I can tell it doesn't shed light on whatever is happening with %*s or the %5.2f (not to mention the 3 apparent placeholders followed by 4 arguments) above?!?

    Read the article

  • Application creashing in saveAction of Coredata iphone sdk

    - by neha
    Hi all, In my application I'm inserting data using Coredata like this: GoodWork * newGoodwork = (GoodWork *)[NSEntityDescription insertNewObjectForEntityForName:@"GoodWork" inManagedObjectContext:self.managedObjectContext]; // Step 2: Set Properties [newGoodwork setEletitle:[NSString stringWithFormat:@"%@", aGoodwork.eletitle]]; [newGoodwork setEletxt:[NSString stringWithFormat:@"%@", aGoodwork.eletxt]]; [newGoodwork setSortId:[NSNumber numberWithInt:sortId]]; // Step 3: Save Object [self saveAction]; Everythinng is working fine but in saveAction which is: - (void)saveAction { NSError *error; if (![self.managedObjectContext save:&error]) { NSLog(@"Unresolved Core Data Save error %@, %@", error, [error userInfo]); exit(-1); } } My application is crashing after processing if condition. I'm not inserting all the fields in the entity "Goodwork". Can that be the reason? Thanx in advance.

    Read the article

  • Make UILabel show "No results" instead of "nan"

    - by Mike Rychev
    I have a small app, where user can make some calculations and solve equations. For example, if in a square equation discriminant is less than zero, the x1 and x2 values are "nan", so when I assign x1 and x2 values to UILabels they show "nan" as well. Writing a lot of if's like if(D<0) [label setText:[NSString stringWithFormat: @"No solutions"]]; Doesn't help-there are too many cases. I want to check if after [label setText:[NSString stringWithFormat: @"%f", x]]; label's value is "nan", the label's value will be set to @"No solutions". Doing simple if(label==@"nan") { //code } doesn't help. Thanks in advance!

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >