Search Results

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

Page 16/25 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Why this kind of release doesn't work?

    - by parkyprg
    Hello, I have a newbie question about the following: - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { NSArray *anArray; anArray = [dictionary objectForKey: [NSString stringWithFormat:@"%d", section]]; //here dictionary is of type NSDictionary, initialized in another place. AnObject *obj = [[AnObject alloc] init]; obj = [anArray objectAtIndex:0]; [anArray release]; return obj.title; } If I run it as it is I will get an error. If I don't put [anArray release] it works just fine. I don't quite understand why is this happening? Thanks.

    Read the article

  • IOS 7 Table cell not show

    - by user2855572
    I am getting very strange problem in my app. I am creating table view cell dynamically.My problem is that textlable is not showing. Code was working on ios 5 and ios 6 but not working on ios 7 it is giving problem.Anybody help me NSString *Str=[NSString stringWithFormat:@"%@",[dateCalcuArray objectAtIndex:indexPath.row]]; Str=[Str stringByReplacingOccurrencesOfString:@"(" withString:@""]; Str=[Str stringByReplacingOccurrencesOfString:@")" withString:@""]; Str=[Str stringByReplacingOccurrencesOfString:@"\"" withString:@""]; ipad_Cell.datelbl.text=Str; ipad_Cell.datelbl.textColor=[UIColor whiteColor];

    Read the article

  • Objective-c when to release objects

    - by Chris
    -(IBAction)registerUpdate:(id)sender { HTTPRequest* request = [[HTTPRequest alloc] initWithUrl:@"http://www.yahoo.com" delegate:self]; [request doRequest]; } The HTTPRequest makes an asynchronous request and calls the onHTTPResponse method in the current class. My question is do I have to release request? My guess is that I'm supposed to make it an instance variable? [NSString stringWithFormat:@"Data received: %@", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]]; How would I release that string object, or should I assign it to a variable?

    Read the article

  • problem in playing next song in the avaudioplayer

    - by Rajashekar
    Hello friends my delegate method looks like this. after the first song is played it goes into this method and plays the second song , however when the second song is done playing it stops. it does not go into the delegate method.i need to play all the songs continuously. i am not sure, why. can someone help me. (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)p successfully:(BOOL)flag { if (flag == NO) NSLog(@"Playback finished unsuccessfully"); else { //[player stop]; index++; NSLog(@"%d",index); path=[[NSBundle mainBundle] pathForResource:[songlist objectAtIndex:index] ofType:@"mp3"]; [player initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; [songlabel2 setTitle:[songlist objectAtIndex:index]]; [endtime setText:[NSString stringWithFormat:@"%.2f",[player duration]/100]]; [player play]; } }

    Read the article

  • Get current location using CLLocationCoordinate2D

    - by Mobility
    I am trying to get current location of user using CLLocationCoordinate2D. I want the values in the format like CLLocationCoordinate2D start = {-28.078694,153.382844 }; So that I can use them like following: NSString *urlAddress = [NSString stringWithFormat:@"http://maps.google.com/?saddr=%1.6f,%1.6f&daddr=%1.6f,%1.6f", start.latitude, start.longitude, destination.latitude, destination.longitude]; I used CLLocation *location = [[CLLocation alloc]init ]; CLLocationDegrees currentLatitude = location.coordinate.latitude; CLLocationDegrees currentLongitude = location.coordinate.longitude; to get current lat & long. But I am getting 0.000 for both when I try to test. I am testing on iPhone 4s. If there is any sample code, it will be great.

    Read the article

  • Convert "minutes since midnight" to time (convert to NSDate?)

    - by Canada Dev
    I am getting some open/closed times as integers since midnight. For example: "1140" = 19:00 (or 7 pm if you will) or; "570" = 9:30 (or 9.30 am) I can easily get the time in European format, just by doing doing a simple calculation and formatting: [NSString stringWithFormat:@"%d:00", (T / 60)] However, this doesn't work for half hours, such as "570 minutes since midnight". Also, I run into problems if I want to include a bit of localization, because some people may prefer AM/PM times. Does NSDate include a method for easily implementing times using the above? Or can anyone tell me how I would at least convert a time like "570 minutes since midnight" to 9:30 properly. Right now it obviously won't write the :30 part. Thank you

    Read the article

  • Downloading image from server without file extension (NSData to UIImage)

    - by Msencenb
    From my server I'm pulling down a url that is supposed to simply be a profile image. The relevant code for pulling down the image from the urls is this: NSString *urlString = [NSString stringWithFormat:@"%@%@",kBaseURL,profile_image_url]; profilePic = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]]; My url is in the format (note no file extension on the end since its dynamically rendered) localhost:8000/people/1/profile_image If I load the url in my browser the image displays; however the code above for pulling down the UIImage does not work. I've verified that the code does pull an image from a random site on the interwebs. Any thoughts on why this is happening?

    Read the article

  • Crashing Strings.... :( objective-c

    - by Ruiter
    I have in the .h file : NSString *dataHML; NSString *dataHML2; NSString *dataHML3; NSString *dataHML4; NSString *dataHML5; NSString *dataHML6; NSString *dataHMLtotal; in the .m file i merge them with : NSString *dataHtmlTotal = [NSString stringWithFormat:@"%@%@%@%@%@%@", dataHtml, dataHtml2, dataHtml3, dataHtml4,dataHtml5,dataHtml6]; But unfortunately it crashes at some point because of this. Could anyone give me a other solution and post it please, because i already tried nsuserdefault or a nsarray, but without i coudn't get it working :(

    Read the article

  • problem in array of shooter sprites which contain different colour bubbles

    - by prakash s
    everyone i am developing bubble shooter game in cocos2d I have placed shooter array which contain different color bubbles like this 00000000 it is 8 bubbles array if i tap the screen, first bubbles should move for shooting the target .png .And if i again tap the screen again 2nd position bubble should move for shooting the target.png bubbles,how it will possible for me because i have already created the array of target which contain different color bubbles, here i write the code : - (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // Choose one of the touches to work with UITouch *touch = [touches anyObject]; CGPoint location = [touch locationInView:[touch view]]; location = [[CCDirector sharedDirector] convertToGL:location]; // Set up initial location of projectile CGSize winSize = [[CCDirector sharedDirector] winSize]; NSMutableArray * movableSprites = [[NSMutableArray alloc] init]; NSArray *images = [NSArray arrayWithObjects:@"1.png", @"2.png", @"3.png", @"4.png",@"5.png",@"6.png",@"7.png", @"8.png", nil]; for(int i = 0; i < images.count; ++i) { int index = (arc4random() % 8)+1; NSString *image = [NSString stringWithFormat:@"%d.png", index]; CCSprite*projectile = [CCSprite spriteWithFile:image]; //CCSprite *projectile = [CCSprite spriteWithFile:@"3.png" rect:CGRectMake(0, 0,256,256)]; [self addChild:projectile]; [movableSprites addObject:projectile]; float offsetFraction = ((float)(i+1))/(images.count+1); //projectile.position = ccp(20, winSize.height/2); //projectile.position = ccp(18,0 ); //projectile.position = ccp(350*offsetFraction, 20.0f); projectile.position = ccp(10/offsetFraction, 20.0f); // projectile.position = ccp(projectile.position.x,projectile.position.y); // Determine offset of location to projectile int offX = location.x - projectile.position.x; int offY = location.y - projectile.position.y; // Bail out if we are shooting down or backwards if (offX <= 0) return; // Ok to add now - we've double checked position //[self addChild:projectile]; // Determine where we wish to shoot the projectile to int realX = winSize.width + (projectile.contentSize.width/2); float ratio = (float) offY / (float) offX; int realY = (realX * ratio) + projectile.position.y; CGPoint realDest = ccp(realX, realY); // Determine the length of how far we're shooting int offRealX = realX - projectile.position.x; int offRealY = realY - projectile.position.y; float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY)); float velocity = 480/1; // 480pixels/1sec float realMoveDuration = length/velocity; // Move projectile to actual endpoint [projectile runAction:[CCSequence actions: [CCMoveTo actionWithDuration:realMoveDuration position:realDest], [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], nil]]; // Add to projectiles array projectile.tag = 1; [_projectiles addObject:projectile]; } }

    Read the article

  • Cocos2d score resetting is messing up (long post warning)

    - by Jhon Doe
    The score is not resetting right at all,I am trying to make a high score counter where every time you passed previous high score it will update.However, right now it is resetting during the game. For example if I had high score of 2 during the game it will take 3 points just to put it up to 3 as high score instead of keep going up until it is game over. I have came to the conclusion that I need to reset it in gameoverlayer so it won't reset during game. I have been trying to to do this but no luck. hello world ./h #import "cocos2d.h" // HelloWorldLayer @interface HelloWorldLayer : CCLayer { int _score; int _oldScore; CCLabelTTF *_scoreLabel; } @property (nonatomic, assign) CCLabelTTF *scoreLabel; hello world init ./m _score = [[NSUserDefaults standardUserDefaults] integerForKey:@"score"]; _oldScore = -1; self.scoreLabel = [CCLabelTTF labelWithString:@"" dimensions:CGSizeMake(100, 50) alignment:UITextAlignmentRight fontName:@"Marker Felt" fontSize:32]; _scoreLabel.position = ccp(winSize.width - _scoreLabel.contentSize.width, _scoreLabel.contentSize.height); _scoreLabel.color = ccc3(255,0,0); [self addChild:_scoreLabel z:1]; hello world implement ./m - (void)update:(ccTime)dt { NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init]; CGRect projectileRect = CGRectMake( projectile.position.x - (projectile.contentSize.width/2), projectile.position.y - (projectile.contentSize.height/2), projectile.contentSize.width, projectile.contentSize.height); BOOL monsterHit = FALSE; NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init]; for (CCSprite *target in _targets) { CGRect targetRect = CGRectMake( target.position.x - (target.contentSize.width/2), target.position.y - (target.contentSize.height/2), target.contentSize.width, target.contentSize.height); if (CGRectIntersectsRect(projectileRect, targetRect)) { CCParticleFire* explosion = [[CCParticleFire alloc] initWithTotalParticles:200]; explosion.texture =[[CCTextureCache sharedTextureCache] addImage:@"sun.png"]; explosion.autoRemoveOnFinish = YES; explosion.startSize = 20.0f; explosion.speed = 70.0f; explosion.anchorPoint = ccp(0.5f,0.5f); explosion.position = target.position; explosion.duration = 1.0f; [self addChild:explosion z:11]; [explosion release]; monsterHit = TRUE; Monster *monster = (Monster *)target; monster.hp--; if (monster.hp <= 0) { [targetsToDelete addObject:target]; [[SimpleAudioEngine sharedEngine] playEffect:@"splash.wav"]; _score ++; } break; } } for (CCSprite *target in targetsToDelete) { [_targets removeObject:target]; [self removeChild:target cleanup:YES]; } if (targetsToDelete.count > 0) { [ projectilesToDelete addObject:projectile]; } [targetsToDelete release]; if (_score > _oldScore) { _oldScore = _score; [_scoreLabel setString:[NSString stringWithFormat:@"score%d", _score]]; [[NSUserDefaults standardUserDefaults] setInteger:_oldScore forKey:@"score"]; _score = 0; } } - (void)update:(ccTime)dt { NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init]; CGRect projectileRect = CGRectMake( projectile.position.x - (projectile.contentSize.width/2), projectile.position.y - (projectile.contentSize.height/2), projectile.contentSize.width, projectile.contentSize.height); BOOL monsterHit = FALSE; NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init]; for (CCSprite *target in _targets) { CGRect targetRect = CGRectMake( target.position.x - (target.contentSize.width/2), target.position.y - (target.contentSize.height/2), target.contentSize.width, target.contentSize.height); if (CGRectIntersectsRect(projectileRect, targetRect)) { CCParticleFire* explosion = [[CCParticleFire alloc] initWithTotalParticles:200]; explosion.texture =[[CCTextureCache sharedTextureCache] addImage:@"sun.png"]; explosion.autoRemoveOnFinish = YES; explosion.startSize = 20.0f; explosion.speed = 70.0f; explosion.anchorPoint = ccp(0.5f,0.5f); explosion.position = target.position; explosion.duration = 1.0f; [self addChild:explosion z:11]; [explosion release]; monsterHit = TRUE; Monster *monster = (Monster *)target; monster.hp--; if (monster.hp <= 0) { [targetsToDelete addObject:target]; [[SimpleAudioEngine sharedEngine] playEffect:@"splash.wav"]; _score ++; } break; } } for (CCSprite *target in targetsToDelete) { [_targets removeObject:target]; [self removeChild:target cleanup:YES]; } if (targetsToDelete.count > 0) { [projectilesToDelete addObject:projectile]; } [targetsToDelete release]; if (_score > _oldScore) { _oldScore = _score; [_scoreLabel setString:[NSString stringWithFormat:@"score%d", _score]]; [[NSUserDefaults standardUserDefaults] setInteger:_oldScore forKey:@"score"]; _score = 0; } The game overlayer .h file game over @interface GameOverLayer : CCLayerColor { CCLabelTTF *_label; CCSprite * background; int _score; int _oldScore; } @property (nonatomic, retain) CCLabelTTF *label; @end @interface GameOverScene : CCScene { GameOverLayer *_layer; } @property (nonatomic, retain) GameOverLayer *layer; @end .m file gameover #import "GameOverLayer.h" #import "HelloWorldLayer.h" #import "MainMenuScene.h" @implementation GameOverScene @synthesize layer = _layer; - (id)init { if ((self = [super init])) { self.layer = [GameOverLayer node]; [self addChild:_layer]; } return self; } - (void)dealloc { [_layer release]; _layer = nil; [super dealloc]; } @end @implementation GameOverLayer @synthesize label = _label; -(id) init { if( (self=[super initWithColor:ccc4(0,0,0,0)] )) { CGSize winSize = [[CCDirector sharedDirector] winSize]; self.label = [CCLabelTTF labelWithString:@"" fontName:@"Arial" fontSize:32]; _label.color = ccc3(225,0,0); _label.position = ccp(winSize.width/2, winSize.height/2); [self addChild:_label]; [self runAction:[CCSequence actions: [CCDelayTime actionWithDuration:3], [CCCallFunc actionWithTarget:self selector:@selector(gameOverDone)], nil]]; _score=0; }

    Read the article

  • iphone xcode annotation pin drop with slider value change also remove

    - by chirag
    i have to add annotation pin on location with UIslider Value change .... this is code where i add annotation (MKAnnotationView *) mapView:(MKMapView *)mapView1 viewForAnnotation:(id ) annotation{ MKAnnotationView* annotationView = nil; NSString* identifier = @"Pin"; MyAnnotationView* annView = (MyAnnotationView*)[mapView1 dequeueReusableAnnotationViewWithIdentifier:identifier]; // annotationView.leftCalloutAccessoryView = myImage; //myImage = [UIButton buttonWithType:UIButtonTypeCustom]; // [myImage setImage:[UIImage imageNamed:@"mark.png"]forState:UIControlStateNormal]; //Property_Photo UIButton *mybtn = [UIButton buttonWithType:UIButtonTypeCustom]; if([annotation isKindOfClass:[AddressAnnotation class]]){ AddressAnnotation x=(AddressAnnotation)annotation; mybtn.frame = CGRectMake(0, 0, 35, 35); mybtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; mybtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter; [mybtn setImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal]; [mybtn setTitle:[NSString stringWithFormat:@"%@",[x getID]] forState:UIControlStateDisabled]; [mybtn addTarget:self action:@selector(btnShowProperty:) forControlEvents:UIControlEventTouchUpInside]; ((IMOVEISAppDelegate*)[[UIApplication sharedApplication]delegate]).strPropertyPrice = [[myTblArray objectAtIndex:imgIndex]valueForKey:@"Property_Price"]; NSLog(@"property price: %@",((IMOVEISAppDelegate*)[[UIApplication sharedApplication]delegate]).strPropertyPrice); if(nil == annView) { ///if(annView!=nil && [annView retainCount]>0){ [annView release]; annView=nil; } annView = [[[MyAnnotationView alloc] initWithAnnotation:x reuseIdentifier:identifier] autorelease]; if(Objslider.value==10){ [myMapView removeAnnotations:myMapView.annotations]; } } NSURL *imgURL = [NSURL URLWithString:[[myTblArray objectAtIndex:imgIndex]valueForKey:@"Property_Photo"]]; UIImage *imgPhoto = [UIImage imageWithData:[NSData dataWithContentsOfURL:imgURL]]; UIImageView *pinImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0,35, 35)]; imgIndex++; [pinImgView setImage:imgPhoto]; annView.rightCalloutAccessoryView = mybtn; annView.leftCalloutAccessoryView = pinImgView; [annView setBackgroundColor:[UIColor clearColor]]; } [annView setEnabled:YES]; annView.canShowCallout = YES; annView.calloutOffset = CGPointMake(-5, 5); annotationView = annView; return annotationView; }

    Read the article

  • UITableView UITableViewCell not reloading on reloadData

    - by David van Dugteren
    This question has been asked a few times now, but there exists no answer on the web that has solved the problem for me yet... See the code: { const NSInteger TOP_LABEL_TAG = 1001; static NSString *CellIdentifier = @"CellIdentifier"; UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } getAQuestionToAnswer = [[QuestionsToAnswer sharedInstance] getLatestLoadedQuestion]; UILabel *topLabel; topLabel = [[[UILabel alloc] initWithFrame: CGRectMake ( 50, 18, 260, 75)] autorelease]; [cell.contentView addSubview:topLabel]; topLabel.tag = TOP_LABEL_TAG; topLabel.backgroundColor = [UIColor clearColor]; topLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0]; topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0]; [topLabel setFont:[UIFont fontWithName:@"MarkerFelt-Thin" size:13]]; topLabel.numberOfLines = 4; topLabel = (UILabel *)[cell viewWithTag:TOP_LABEL_TAG]; topLabel.text = [NSString stringWithFormat:@"%@", [getAQuestionToAnswer valueForKey:@"question"] ]; Some code is omitted but the basics is there, I'm updating by means of a shake gesture, the NSLog confirms that the getAQuestionToAnswer is indeed updated with a new question after the gesture. Yet at run time, no matter what I do... e.g. [self.tableview reloaddata]; nothing works. It just doesn't want to refresh.

    Read the article

  • MkMapView Zoom Level

    - by meetS
    I m using MkMapView with google maps.I succeed to show map view and address with annotation pin.But I want increased zoom level.How Can I Set it programmatically?? (void) showMyAddress { //Hide the keypad MKCoordinateRegion region; MKCoordinateSpan span; span.latitudeDelta=0.2; span.longitudeDelta=0.2; CLLocationCoordinate2D location = [self addressLocation]; region.span=span; region.center=location; if(addAnnotation != nil) { [mapView removeAnnotation:addAnnotation]; [addAnnotation release]; addAnnotation = nil; } addAnnotation = [[AddAnnotation alloc] initWithCoordinate:location ]; [addAnnotation setMTitle:@"abc"]; [addAnnotation setMSubTitle:@"def."] [mapView addAnnotation:addAnnotation]; [mapView setRegion:region animated:TRUE]; [mapView regionThatFits:region]; } -(CLLocationCoordinate2D) addressLocation { NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", [@"abc" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSStringEncodingConversionAllowLossy error:nil]; NSArray *listItems = [locationString componentsSeparatedByString:@","]; double latitude = 0.0; double longitude = 0.0; if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) { latitude = [[listItems objectAtIndex:2] doubleValue]; longitude = [[listItems objectAtIndex:3] doubleValue]; } else { } CLLocationCoordinate2D location; location.latitude = latitude; location.longitude = longitude; return location; }

    Read the article

  • UIWebView is ignoring cookies?!

    - by A. Miladinovic
    Hello everybody, I am creating an app for the iPhone that fetches a specific page from a website, but to be able to view this site you need to log in with a username and a password. I've created this code: NSString *urlAddress = @"http://www.wdg-hamburg.de"; NSURL *url = [NSURL URLWithString:urlAddress]; NSString *post = @"name=loginname&pass=pass&form_id=user_login&op=Anmelden"; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod: @"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; [vPlan loadRequest:request]; But I am not logged in at the UIWebView! I am logging NSHTTPCookieStorage to the console and it shows me the necessary cookie, but I dont get logged in. Does anybody knows how I can fix that? Kind regards, A. Miladinovic

    Read the article

  • http stream of baselineh264 doesnt seem to work in my MPMoviePlayerViewController

    - by theprojectabot
    Here is some code... I have a stream that works correctly if I view with safari on the iphone or quicktimex on the mac... but the stream doesnt view in my code for the ipad simulator - (IBAction)clickedOpenMovie:(id)sender { NSString *myString = [NSString stringWithFormat:@"http://myipofstreamingserver:1935/live/aStream/playlist.m3u8"]; //NSString *myString = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"720p5994-prores-hq_iPhone_320x240.m4v"]; NSURL *myURL = [NSURL fileURLWithPath:myString]; [self playMovieAtURL:myURL]; } -(void)playMovieAtURL:(NSURL*)theURL { //CGRect moviePlayerFrame = CGRectMake(20, 33, 100, 100); //UIView playerView = [[[UIView alloc] initWithFrame:moviePlayerFrame] autorelease]; MPMoviePlayerViewController* movieViewController = [[MPMoviePlayerViewController alloc] initWithContentURL:theURL]; //theMovie.scalingMode = MPMovieScalingModeNone; //theMovie. = MPMovieControlStyleFullscreen; //movieViewController.controlStyle = MPMovieControlModeDefault; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMovieFinishedCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:movieViewController]; //UIViewController *movieViewController = [[UIViewController alloc] initWithContentURL:theURL]; [self presentMoviePlayerViewControllerAnimated:movieViewController]; //[theMovie play]; }

    Read the article

  • How to download a wav file from the web to a location on iPhone using NSFileHandle and NSURLConnecti

    - by Jinru
    Hi all, I want to download a wav file from a web service, cache it on the iphone and playback it using AVAudioPlayer. Using NSFileHandle and NSURLConnection seems a viable solution when dealing with relatively large files. However, after running the app in the simulator I don't see any saved file under the defined directory (NSHomeDirectory/tmp). Below is my basic code. Where am I doing wrong? Any thoughts are appreciated! #define TEMP_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"] - (void)downloadToFile:(NSString*)name { NSString* filePath = [[NSString stringWithFormat:@"%@/%@.wav", TEMP_FOLDER, name] retain]; self.localFilePath = filePath; // set up FileHandle self.audioFile = [[NSFileHandle fileHandleForWritingAtPath:localFilePath] retain]; [filePath release]; // Open the connection NSURLRequest* request = [NSURLRequest requestWithURL:self.webURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; } #pragma mark - #pragma mark NSURLConnection methods - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data { [self.audioFile writeData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error { NSLog(@"Connection failed to downloading sound: %@", [error description]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [connection release]; [audioFile closeFile]; }

    Read the article

  • UIImagePickerController Save to Disk then Load to UIImageView

    - by Harley Gagrow
    Hi, I have a UIImagePickerController that saves the image to disk as a png. When I try to load the PNG and set a UIImageView's imageView.image to the file, it is not displaying. Here is my code: (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; NSData *imageData = UIImagePNGRepresentation(image); // Create a file name for the image NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setTimeStyle:NSDateFormatterShortStyle]; [dateFormatter setDateStyle:NSDateFormatterShortStyle]; NSString *imageName = [NSString stringWithFormat:@"photo-%@.png", [dateFormatter stringFromDate:[NSDate date]]]; [dateFormatter release]; // Find the path to the documents directory NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // Now we get the full path to the file NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName]; // Write out the data. [imageData writeToFile:fullPathToFile atomically:NO]; // Set the managedObject's imageLocation attribute and save the managed object context [self.managedObject setValue:fullPathToFile forKey:@"imageLocation"]; NSError *error = nil; [[self.managedObject managedObjectContext] save:&error]; [self dismissModalViewControllerAnimated:YES]; } Then here is how I try to load it: self.imageView.backgroundColor = [UIColor lightGrayColor]; self.imageView.frame = CGRectMake(10, 10, 72, 72); if ([self.managedObject valueForKey:@"imageLocation"] != nil) { NSLog(@"Trying to load the imageView with: %@", [self.managedObject valueForKey:@"imageLocation"]); UIImage *image = [[UIImage alloc] initWithContentsOfFile:[self.managedObject valueForKey:@"imageLocation"]]; self.imageView.image = image; } else { self.imageView.image = [UIImage imageNamed:@"no_picture_taken.png"]; } I get the message that it's trying to load the imageView in the debugger, but the image is never displayed in the imageView. Can anyone tell me what I've got wrong here? Thanks a bunch.

    Read the article

  • UIImagePickerController does nothing when using camera after I hit "Use" button

    - by wgpubs
    Code below. When I hit the "Use" button after taking a picture ... the application becomes totally unresponsive. Any ideas what I'm doing wrong? The "addPlayer:" method is called when a button is pressed on the UIViewController's view. Thanks - (IBAction) addPlayers: (id)sender{ // Show ImagePicker UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.delegate = self; // If camera is available use it and display custom overlay view so that user can add as many pics // as they want without having to go back to parent view if([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) { imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; } else { imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; } [self presentModalViewController:imagePicker animated:YES]; [imagePicker release]; } - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { // Grab original image UIImage *photo = [info objectForKey:UIImagePickerControllerOriginalImage]; // Resize photo first to reduce memory consumption [self.photos addObject:[photo scaleToSize:CGSizeMake(200.0f, 300.0f)]]; // Enable *PLAY* button if photos > 1 if([self.photos count] > 1) btnStartGame.enabled = YES; // Update player count label lblPlayerCount.text = [NSString stringWithFormat:@"%d", [self.photos count]]; // Dismiss picker if not using camera picker dismissModalViewControllerAnimated:YES]; }

    Read the article

  • How do I convert an NSMutableString to NSString when using Frameworks?

    - by BWHazel
    I have written an Objective-C framework which builds some HTML code with NSMutableString which returns the value as an NSString. I have declared an NSString and NSMutableString in the inteface .h file: NSString *_outputLanguage; // Tests language output NSMutableString *outputBuilder; NSString *output; This is a sample from the framework implementation .m code (I cannot print the actual code as it is proprietary): -(NSString*)doThis:(NSString*)aString num:(int)aNumber { if ([outputBuilder length] != 0) { [outputBuilder setString:@""]; } if ([_outputLanguage isEqualToString:@"html"]) { [outputBuilder appendString:@"Some Text..."]; [outputBuilder appendString:aString]; [outputBuilder appendString:[NSString stringWithFormat:@"%d", aNumber]]; } else if ([_outputLanguage isEqualToString:@"xml"]) { [outputBuilder appendString:@"Etc..."]; } else { [outputBuilder appendString:@""]; } output = outputBuilder; return output; } When I wrote a text program, NSLog simply printed out "(null)". The code I wrote there was: TheClass *instance = [[TheClass alloc] init]; NSString *testString = [instance doThis:@"This String" num:20]; NSLog(@"%@", testString); [instance release]; I hope this is enough information!

    Read the article

  • Custom UITableViewCell won't redraw on setNeedsDisplay

    - by Andrew Portner
    I created a custom UITableViewCell class with a UIButton, a UIImage, and two UILabels. The button and the image are overlayed on top of each other, and only one is displayed at a time. The expected behavior is you touch on the button, the button disappears, and it displays the image. The UITableViewCells are set to be reused. Here's my code: Constructor: - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) { unheartButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain]; unheartButton.backgroundColor = [UIColor clearColor]; unheartButton.frame = CGRectMake(10, 13, 20, 18); [unheartButton addTarget:self action:@selector(onButtonClick:) forControlEvents:UIControlEventTouchUpInside]; [unheartButton setBackgroundImage:[UIImage imageNamed:@"redheart.png"] forState:UIControlStateNormal]; imageView = [[UIImageView alloc] init]; imageView.frame = CGRectMake(12, 13, 16, 16); NSMutableArray *array = [[NSMutableArray alloc] init]; for (int ndx = 1; ndx < 13; ndx++) { [array addObject:[UIImage imageNamed:[NSString stringWithFormat:@"icon-loading-%d (dragged).tiff", ndx]]]; } imageView.animationImages = array; imageView.animationDuration = 1; imageView.hidden = YES; [array release]; [self.contentView addSubview:imageView]; [self.contentView addSubview:unheartButton]; return self; } } Button click: - (IBAction) onButtonClick: (id) sender { unheartButton.hidden = YES; imageView.hidden = NO; [imageView startAnimating]; [self setNeedsDisplay]; [self.contentView setNeedsDisplay]; [self.unheartButton setNeedsDisplay]; [self.imageView setNeedsDisplay]; } I'm calling setNeedsDisplay on everything, but nothing seems to happen. If I scroll off the screen and back up, the button is hidden and now the loading icon is shown, but this only happens after a scroll. I'm not sure what I need to do to get the cell to repaint.

    Read the article

  • Twitter integration and iOS5: semantic and parsing issues

    - by Tyler
    I was using some of Apple's example code to write the Twitter integration for my app. However, I get a whopping amount of errors (mostly being Semantic and parse errors). How can this be solved? -(IBAction)TWButton:(id)sender { ACAccountStore *accountstore = [[ACAccountStore alloc] init]; //Make sure to retrive twitter accounts ACAccountType *accountType = [accountstore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; [accountstore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) { if (granted) [{ NSArray *accountsArray = [accountstore accountsWithAccountType:accountType]; if ([accountsArray count] > 0) { ACAccount *twitterAccount = [accountsArray objectAtIndex:0]; TWRequest *postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@"http://api.twitter.com/1/statuses/update.json"] parameters:[NSDictionary dictionaryWithObject:[@"Tweeted from iBrowser" forKey:@"status"] requestMethod:TWRequestMethodPOST]; [postRequest setAccount:twitterAccount]; [postRequest preformRequestWithHandeler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { NSString *output = [NSString stringWithFormat:@"HTTP response status: %i", [urlResponse statusCode]]; [self preformSelectorOnMainThread:@selector(displaytext:) withObject:output waitUntilDone:NO]; }]; } }]; } //Now lets see if we can actually tweet -(void)canTweetStatus { if ([TWTweetComposeViewController canSendTweet]) { self.TWButton.enabled = YES self.TWButton.alpha = 1.0f; }else{ self.TWButton.enabled = NO self.TWButton.alpha = 0.5f; } }

    Read the article

  • OCUnit & NSBundle

    - by kpower
    I created OCUnit test in concordance with "iPhone Development Guide". Here is the class I want to test: // myClass.h #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface myClass : NSObject { UIImage *image; } @property (readonly) UIImage *image; - (id)initWithIndex:(NSUInteger)aIndex; @end // myClass.m #import "myClass.m" @implementation myClass @synthesize image; - (id)init { return [self initWithIndex:0]; } - (id)initWithIndex:(NSUInteger)aIndex { if ((self = [super init])) { NSString *name = [[NSString alloc] initWithFormat:@"image_%i", aIndex]; NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"png"]; image = [[UIImage alloc] initWithContentsOfFile:path]; if (nil == image) { @throw [NSException exceptionWithName:@"imageNotFound" reason:[NSString stringWithFormat:@"Image (%@) with path \"%@\" for current index (%i) wasn't found.", [name autorelease], path, aIndex] userInfo:nil]; } [path release]; } return self; } - (void)dealloc { [image release]; [super dealloc]; } @end And my unit-test (LogicTests target): // myLogic.m #import <SenTestingKit/SenTestingKit.h> #import <UIKit/UIKit.h> #import "myClass.h" @interface myLogic : SenTestCase { } - (void)testTemp; @end @implementation myLogic - (void)testTemp { STAssertNoThrow([[myClass alloc] initWithIndex:0], "myClass initialization error"); } @end All necessary frameworks, "myClass.m" and images added to target. But on build I have an error: [[myClass alloc] initWithIndex:0] raised Image (image_0) with path \"(null)\" for current index (0) wasn't found.. myClass initialization error This code (initialization) works fine in application itself (main target) and later displays correct image. I've also checked my project folder (build/Debug-iphonesimulator/LogicTests.octest/) - there are LogicTests, Info.plist and necessary image files (image_0.png is one of them). What's wrong?

    Read the article

  • UISearchDisplayController "shouldReloadTableForSearchString return NO" reloads table

    - by Jeena
    Why does my UISearchDisplayController show "No results" even if the shouldReloadTableForSearchString method returns NO? Shouldn't it just do nothing and stay black? How can I prevent it from doing so? #import "RootViewController.h" #pragma mark Table view methods - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (tableView == self.searchDisplayController.searchResultsTableView) { return 0; } return 10; } // 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. cell.textLabel.text = [NSString stringWithFormat:@"row %d", indexPath.row]; return cell; } #pragma mark SearchController stuff - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString { return NO; } - (void)dealloc { [super dealloc]; } @end

    Read the article

  • Embed Youtube in UIWebView behind transparent img. Wmode transparent and z-index doesn't work

    - by Allisone
    I'm using this code: - (void)embedYouTube:(NSString *)urlString frame:(CGRect)frame { NSString *embedHTML = @"\ <html><head>\ <style type=\"text/css\">\ body {\ background-color: black;\ }\ #container{\ position: relative;\ z-index:1;\ }\ #video,#videoc{\ position:absolute;\ z-index: 1;\ border: none;\ }\ #tv{\ background: transparent url(tv.png) no-repeat;\ width: 320px;\ height: 205px;\ position: absolute;\ top: 0;\ z-index: 999;\ }\ </style>\ </head><body style=\"margin:0\">\ <div id=\"tv\"></div>\ <object id=\"videoc\" width=\"240\" height=\"160\">\ <param name=\"movie\" value=\"%@\"></param>\ <param name=\"wmode\" value=\"transparent\"></param>\ <embed wmode=\"transparent\" id=\"video\" src=\"%@\" type=\"application/x-shockwave-flash\" \ width=\"240\" height=\"160\"></embed>\ </object>\ </body></html>"; NSString *path = [[NSBundle mainBundle] bundlePath]; NSURL *baseURL = [NSURL fileURLWithPath:path]; NSString *html = [NSString stringWithFormat:embedHTML, urlString,urlString]; UIWebView *videoView = [[UIWebView alloc] initWithFrame:frame]; [videoView loadHTMLString:html baseURL:baseURL]; [self.view addSubview:videoView]; [videoView release]; } Its the first time that I use UIWebView and the first time that I use video in iPhone. The video plays, so that's working BUT: I want to have an old school tv (round corners) in foreground with switches and so on. The tv is an image with transparent pixels in the middle, so that a video lying behind the tv will shine through as if the video would be shown on the tv. But first of all the video has a border that I can't remove and second it's always in the foreground. In Safari and in Firefox and Mac it's working. So is it an iPhone thing, could it be that it simply won't work on iPhone ? Or do I have some css/html typos ?

    Read the article

  • Iphone SQLite Databse with german umlauts results in NULL value

    - by Daniel
    Hi guys, I'm quite new to the Iphone development and after search for an answer for 3 hours now, I hope that you guys can give me a hand. My problem is that I have a SQLite Database with german umlauts. Looking at it with a SQLite browser tool shows me that the data is stored with german umlauts, correctly. But selecting fields with german umlauts in it results in a NULL value. I'm already using "stringWithUTF8String", so I don't get the point where the problem is placed. Here is my code: -(void) readSearchFromDatabase { searchFlag = YES; // Setup the database object sqlite3 *database; // Init the SCode Array searchSCodes = [[NSMutableArray alloc] init]; // Open the database from the users filessytem if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { NSString *wildcard =@"%"; // Setup the SQL Statement and compile it NSString *sql = [NSString stringWithFormat:@"SELECT * FROM scode WHERE ta LIKE '%@%@%@' OR descriptionde LIKE '%@%@%@' OR descriptionen LIKE '%@%@%@'", wildcard, searchBar.text, wildcard, wildcard, searchBar.text, wildcard, wildcard, searchBar.text, wildcard, wildcard, searchBar.text, wildcard]; //Creating a const char SQL Statement especially for SQLite const char *sqlStatement = [sql UTF8String]; sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { // Loop through the results and add them to the feeds array while(sqlite3_step(compiledStatement) == SQLITE_ROW) { // Read the data from the result row NSString *aTa = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)]; NSString *aReport = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]; NSString *aDescriptionDE = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)]; NSString *aDescriptionEN = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)]; //Results a NULL value NSLog(@"Output: %@", aDescriptionDE); // Create a new SCode object with the data from the database SCode *searchSCode = [[SCode alloc] initWithTa:aTa report:aReport descriptionDE:aDescriptionDE descriptionEN:aDescriptionEN]; // Add the SCode object to the SCodes Array [searchSCodes addObject:searchSCode]; [searchSCode release]; } } // Release the compiled statement from memory sqlite3_finalize(compiledStatement); } sqlite3_close(database); }

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >