Search Results

Search found 477 results on 20 pages for 'nsdata'.

Page 12/20 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • iPhone: custom cell is overlaping with each other

    - by Nandakishore
    hi i am working on Table view, my Table view first custom cell is over ride other cell when Scrolling this is my code import UIKit/UIKit.h @interface MyTweetViewController : UIViewController { IBOutlet UITableView *tweetsTableView; NSMutableArray *tweetArray; } @property (nonatomic, retain) IBOutlet UITableView *tweetsTableView; @end import "MyTweetViewController.h" @implementation MyTweetViewController @synthesize tweetsTableView; (void)viewDidLoad { tweetArray = [[NSMutableArray alloc] init]; [tweetsTableView setBackgroundColor:[UIColor clearColor]]; [super viewDidLoad]; } 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 [tweetArray count]; } (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 80; } - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { [cell setBackgroundColor:[UIColor clearColor]]; } //Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *identifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; if(!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:identifier]; cell.selectionStyle = UITableViewCellSelectionStyleNone; } cell.accessoryType = UITableViewCellAccessoryNone; UILabel * name = [[UILabel alloc]initWithFrame:CGRectMake(72,3,242,15)]; name.text = (NSString*)[(Tweet*)[tweetArray objectAtIndex:indexPath.row] userName]; [name setFont:[UIFont fontWithName:@"Helvetica" size:14]]; name.textColor=[UIColor colorWithRed:250 green:250 blue:210 alpha:0.5]; [name setBackgroundColor:[UIColor clearColor]]; UILabel * tweetLabel = [[UILabel alloc]initWithFrame:CGRectMake(72,20,242,60)]; tweetLabel.text = (NSString*)[(Tweet*)[tweetArray objectAtIndex:indexPath.row] tweet]; tweetLabel.numberOfLines = 3; tweetLabel.textColor=[UIColor colorWithRed:252 green:148 blue:31 alpha:1]; [tweetLabel setFont:[UIFont fontWithName:@"Helvetica" size:12]]; [tweetLabel setBackgroundColor:[UIColor clearColor]]; NSLog(@" lblUserTweet : %@ ",name.text); UIImageView *myImage = [[UIImageView alloc]initWithFrame:CGRectMake(6,3,58,49)]; NSURL url = [NSURL URLWithString:[(Tweet)[tweetArray objectAtIndex:indexPath.row] image_url]]; NSData *data = [NSData dataWithContentsOfURL:url]; [myImage setImage: [UIImage imageWithData:data]]; [cell.contentView addSubview:myImage]; [cell.contentView addSubview:tweetLabel]; [cell.contentView addSubview:name]; return cell; } (void)dealloc { [tweetsTableView release]; [tweetArray release]; [super dealloc]; }

    Read the article

  • Strange behavior: save video recorded within app?

    - by Josue Espinosa
    I allow the user to record a video within my app, then later play it again. When a user records a video, I save the URL of the video, then play the video later from the saved URL. I save the video both in the Photos app and in my app. If I delete the video within the photos app, it still plays. After about 7 days, the video gets deleted. I think I am saving in my tmp directory, but i'm not sure. Here is what I am doing: -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType]; [self dismissViewControllerAnimated:YES completion:nil]; // Handle a movie capture if (CFStringCompare ((__bridge_retained CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) { NSString *moviePath = [NSString stringWithFormat:@"%@",[[info objectForKey:UIImagePickerControllerMediaURL] path]]; NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL]; NSData *videoData = [NSData dataWithContentsOfURL:videoURL]; _justRecordedVideoURL = [NSString stringWithFormat:@"%@",videoURL]; AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; _managedObjectContext = [appDelegate managedObjectContext]; Video *video = [NSEntityDescription insertNewObjectForEntityForName:@"Video" inManagedObjectContext:_managedObjectContext]; [video setVideoData:videoData]; [video setVideoURL:[NSString stringWithFormat:@"%@",videoURL]]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateStyle = NSDateFormatterLongStyle; [dateFormatter setDateStyle:NSDateFormatterLongStyle]; NSDate *date = [dateFormatter dateFromString:[dateFormatter stringFromDate:[NSDate date]]]; NSString *dateAdded = [dateFormatter stringFromDate:date]; [video setDate_recorded:dateAdded]; if(_currentAthlete != nil){ [video setWhosVideo:_currentAthlete]; } NSError *error = nil; if(![_managedObjectContext save:&error]){ //handle dat error } NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *tempPath = [documentsDirectory stringByAppendingFormat:@"/vid1.mp4"]; BOOL success = [videoData writeToFile:tempPath atomically:NO]; if(success == FALSE){ NSLog(@"Video was not successfully saved."); } if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(moviePath)) { UISaveVideoAtPathToSavedPhotosAlbum(moviePath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil); } } } Am I saving it incorrectly? When I go to play the video, it works fine, after a couple days the video will play without audio, then eventually it will be gone. Any ideas why?

    Read the article

  • -[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

  • UIImagePNGRepresentation issues?

    - by disorderdev
    I want to load images from UIImagePickerController, then save the selected photo to my app's document directory. UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; NSData *data1 = UIImagePNGRepresentation(image); NSString *fileName = "1.png"; NSString *path = //get Document path, then add fileName BOOL succ = [data1 writeToFile:path atomically:YES]; but after I save the image to my document, I found that, the image was rotated 90 degree, then I change the method UIImagePNGRepresentation to UIImageJPEGRepresentation, this time it's fine, anyone know what's the problem?

    Read the article

  • iOs receivedData from NSURLConnection is nil

    - by yhl
    I was wondering if anyone could point out why I'm not able to capture a web reply. My NSLog shows that my [NSMutableData receivedData] has a length of 0 the entire run of the connection. The script that I hit when I click my login button returns a string. My NSLog result is pasted below, and after that I've pasted both the .h and .m files that I have. NSLog Result 2012-11-28 23:35:22.083 [12548:c07] Clicked on button_login 2012-11-28 23:35:22.090 [12548:c07] theConnection is succesful 2012-11-28 23:35:22.289 [12548:c07] didReceiveResponse 2012-11-28 23:35:22.290 [12548:c07] didReceiveData 2012-11-28 23:35:22.290 [12548:c07] 0 2012-11-28 23:35:22.290 [12548:c07] connectionDidFinishLoading 2012-11-28 23:35:22.290 [12548:c07] 0 ViewController.h #import <UIKit/UIKit.h> @interface ViewController : UIViewController // Create an Action for the button. - (IBAction)button_login:(id)sender; // Add property declaration. @property (nonatomic,assign) NSMutableData *receivedData; @end ViewController.m #import ViewController.h @interface ViewController () @end @implementation ViewController @synthesize receivedData; - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"didReceiveResponse"); [receivedData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@"didReceiveData"); [receivedData appendData:data]; NSLog(@"%d",[receivedData length]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"connectionDidFinishLoading"); NSLog(@"%d",[receivedData length]); } - (IBAction)button_login:(id)sender { NSLog(@"Clicked on button_login"); NSString *loginScriptURL = [NSString stringWithFormat:@"http://www.website.com/app/scripts/login.php?"]; NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:loginScriptURL]]; NSString *postString = [NSString stringWithFormat:@"&paramUsername=user&paramPassword=pass"]; NSData *postData = [postString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; [theRequest setHTTPMethod:@"POST"]; [theRequest setHTTPBody:postData]; // Create the actual connection using the request. NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; // Capture the response if (theConnection) { NSLog(@"theConnection is succesful"); } else { NSLog(@"theConnection failed"); } } @end

    Read the article

  • nsmutablearray and saving to file

    - by Amir
    hello all, I have class named Shop that contain data members (NSString , NSInteger and nsmutablearray that contain another class(that have also NSString and NSInteger) Now if i use nsmutablearray to hold alist of Shops what is the best way to save the list to file and load it later? again the class Shop contain data memeber that is another class both of the classes have NSString and NSinteger (maybe also NSdata and NSdate) i heard somthing about archiver?? thanks.

    Read the article

  • how to handle multiple NSUrlResponses in iphone

    - by MaheshBabu
    hi folks, i am getting data from .net web services. I am sending two NSURlrequests to the same url, But i need to save those responses separately. for that my code is -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { if (theConnection_LOD ) { [webData_LOD appendData:data]; } if (theConnection_photo) { [webData_photo appendData:data]; } } But it does n't work how can i handle these responses. can any one pls help me. Thank u in advance.

    Read the article

  • GKSession sendDataToAllPeers getting invalid parameter

    - by cb4
    This is my first post and I wanted to start it by thanking the many stackoverflow contributors who will never know how much they helped me out these past several days as I worked to complete my first iOS app. I am indebted to them and to this site for giving them a place to post. To 'pay off' some of that debt, I hope this will help others as I have been helped... So, my app uses the GKPeerPickerController to make a connection to a 2nd device. Once connected, the devices can send text messages to each other. The receiving peer has the message displayed in a UIAlertView. Everything was working fine. Then I decided to experiment with locations and added code to get the current location. I convert it into latitude & longitude in degrees, minutes, and seconds and put them into one NSString. I added a button to my storyboard called 'Send Location' which, when tapped, sends the location to the connected peer. This is where I ran into the problem. Both the send text and send location methods call the sendPacket method with a NSString. sendPacket converts the string to NSData and calls sendDataToAllPeers. When I learned how to capture the error, it was "Invalid parameter for - sendDataToAllPeers:withDataMode:error:". [.....pause.....] Well, this was going to be a question but in writing all this to explain the problem, the answer just dawned on me. Did a few tests and verified it now works. The issue was not in sendDataToAllPeers, it was in the conversion of the NSString (strToSend) to NSData: packet = [strToSend dataUsingEncoding:NSASCIIStringEncoding]; Specifically, it was the degree sign character (little circle, ASCII 176). NSASCIIStringEncoding only includes ASCII characters up to 127 so don't use any above that. I'm sure there was a quicker way to find the problem, but I don't know Objective-C or Xcode's debugging facility well enough yet. Whew! Several hours to discover that little tidbit. I did learn a lot, though, and that's always a good thing!

    Read the article

  • Opening a streaming connection to an HTTP server on iPhone/Cocoa environment?

    - by Paul
    I've been using NSURLConnection to do a HTTP post to establish the connection. I've also implemented the didReceiveData delegagate to process incoming bytes as they become available. As incoming data comes in via didReceiveData, I add the NSData to a data buffer and try parsing the bytesteam if enough data has come in to complete a message segment. I'm having a hard time managing the data buffer (NSMutableData object) to remove bytes that have been parsed to structs. Was curious if there's an easier way. Thanks

    Read the article

  • Application crashing on getting updated information from database using timer and storing it on loca

    - by Amit Battan
    In our multi - user application we are continuously interacting with database. We have a common class through which we are sending POST queries to database and obtaining xml files in return. We are using delegates of NSXMLParser to parse the obtained file. The problem with us is we are facing many crashes in it generally when application is idle and changed data in database is being fetched in background through timer which is invoked after every few seconds. We have also dealt with error handling through try and catch but it proves to be of no use in this case and mostly application crashes with following error : Exception Type: EXC_BAD_ACCESS (SIGBUS) Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000000000020 Strange thing is that many times the fetching of updated data at background works very fine, same methods being successfully executed under similar conditions but suddenly it crashes on one of them. The codes we are using is as follows: // we are using timer in this way: chkOnlineUser=[NSTimer scheduledTimerWithTimeInterval:15 target:mmObject selector:@selector(threadOnlineUser) userInfo:NULL repeats:YES]; // this method being called in timer -(void)threadOnlineUser{//HeartBeat in Thread [NSThread detachNewThreadSelector:@selector(onlineUserRefresh) toTarget:self withObject:nil]; } // this performs actual updation -(void)onlineUserRefresh{ NSAutoreleasePool *pool =[[NSAutoreleasePool alloc]init]; @try{ if(chkTimer==1){ return; } chkTimer=1; if([allUserArray count]==0){ [user parseXMLFileUser:@"all" andFlag:3]; [allUserArray removeAllObjects]; [allUserArray addObjectsFromArray:[user users]]; } [objHeartBeat parseXMLFile:[loginID intValue] timeOut:10]; NSMutableDictionary *tDictOL=[[NSMutableDictionary alloc] init]; tDictOL=[objHeartBeat onLineList]; NSArray *tArray=[[NSArray alloc] init]; tArray=[[tDictOL objectForKey:@"onlineuser"] componentsSeparatedByString:@","]; [loginUserArray removeAllObjects]; for(int l=0;l less than [tArray count] ;l++){ int t;//=[[tArray objectAtIndex:l] intValue]; if([[allUserArray valueForKey:@"Id"] containsObject:[tArray objectAtIndex:l]]){ t = [[allUserArray valueForKey:@"Id"] indexOfObject:[tArray objectAtIndex:l]]; [loginUserArray addObject:[allUserArray objectAtIndex:t]]; } } [onlineTable reloadData]; [logInUserPopUp removeAllItems]; if([loginUserArray count]==1){ [labelLoginUser setStringValue:@"Only you are online"]; [logInUserPopUp setEnabled:YES]; }else{ [labelLoginUser setStringValue:[NSString stringWithFormat:@" %d users online",[loginUserArray count]]]; [logInUserPopUp setEnabled:YES]; } NSMenu *menu = [[NSMenu alloc] initWithTitle:@"menu"]; NSMenuItem *itemOne = [[NSMenuItem alloc] initWithTitle:@"" action:NULL keyEquivalent:@""]; [menu addItem:itemOne]; for(int l=0;l less than [loginUserArray count];l++){ NSString *tempStr= [NSString stringWithFormat:@"%@ %@",[[[loginUserArray objectAtIndex:l] objectForKey:@"user_fname"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]],[[[loginUserArray objectAtIndex:l] objectForKey:@"user_lname"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]]; if(![tempStr isEqualToString:@""]){ NSMenuItem *itemOne = [[NSMenuItem alloc] initWithTitle:tempStr action:NULL keyEquivalent:@""]; [menu addItem:itemOne]; }else if(l==0){ NSMenuItem *itemOne = [[NSMenuItem alloc] initWithTitle:tempStr action:NULL keyEquivalent:@""]; [menu addItem:itemOne]; } } [logInUserPopUp setMenu:menu]; if([lastUpdateTime isEqualToString:@""]){ }else { [self fetchUpdatedInfo:lastUpdateTime]; [self fetchUpdatedGroup:lastUpdateTime];// function same as fetchUpdatedInfo [avObject fetchUpdatedInfo:lastUpdateTime];// function same as fetchUpdatedInfo [esTVObject fetchUpdatedInfo:lastUpdateTime];// function same as fetchUpdatedInfo } lastUpdateTime=[[tDictOL objectForKey:@"lastServerTime"] copy]; } @catch (NSException * e) { [queryByPost insertException:@"MainModule" inFun:@"onlineUserRefresh" excp:[e description] userId:[loginID intValue]]; NSRunAlertPanel(@"Error Panel", @"Main Module- onlineUserRefresh....%@", @"OK", nil, nil,e); } @finally { NSLog(@"Internal Update Before Bye"); chkTimer=0; NSLog(@"Internal Update Bye");// Some time application crashes after this log // Some time application crahses after "Internal Update Bye" log } } // The method which we are using to obtain updated data is of following form: -(void)fetchUpdatedInfo:(NSString *)UpdTime{ @try { if(initAfterLoginComplete==0){ return; } [user parseXMLFileUser:UpdTime andFlag:[loginID intValue]]; [tempUserUpdatedArray removeAllObjects]; [tempUserUpdatedArray addObjectsFromArray:[user users]]; if([tempUserUpdatedArray count]0){ if([contactsView isHidden]){ [topContactImg setImage:[NSImage imageNamed:@"btn_contacts_off_red.png"]]; }else { [topContactImg setImage:[NSImage imageNamed:@"btn_contacts_red.png"]]; } }else { return; } int chkprof=0; for(int l=0;l less than [tempUserUpdatedArray count];l++){ NSArray *tempArr1 = [allUserArray valueForKey:@"Id"]; int s; if([[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"] intValue]==profile_Id){ chkprof=1; } if([tempArr1 containsObject:[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"]]){ s = [tempArr1 indexOfObject:[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"]]; [allUserArray replaceObjectAtIndex:s withObject:[tempUserUpdatedArray objectAtIndex:l]]; }else { [allUserArray addObject:[tempUserUpdatedArray objectAtIndex:l]]; } NSArray *tempArr2 = [tempUser valueForKey:@"Id"]; if([tempArr2 containsObject:[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"]]){ s = [tempArr2 indexOfObject:[[tempUserUpdatedArray objectAtIndex:l] objectForKey:@"Id"]]; [tempUser replaceObjectAtIndex:s withObject:[tempUserUpdatedArray objectAtIndex:l]]; }else { [tempUser addObject:[tempUserUpdatedArray objectAtIndex:l]]; } } NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"user_fname" ascending:YES]; [tempUser sortUsingDescriptors:[NSMutableArray arrayWithObject:sortDescriptor]]; [userListTableView reloadData]; [groupsArray removeAllObjects]; for(int z=0;z less than [tempGroups count];z++){ NSMutableArray *tempMArr=[[NSMutableArray alloc] init]; for(int l=0;l less than [allUserArray count];l++){ if([[[allUserArray objectAtIndex:l] objectForKey:@"GroupId"] intValue]==[[[tempGroups objectAtIndex:z] objectForKey:@"group_id"] intValue]){ [tempMArr addObject:[allUserArray objectAtIndex:l]]; } } [groupsArray insertObject:tempMArr atIndex:z]; [tempMArr release]; tempMArr= nil; } for(int n=0;n less than [tempGroups count];n++){ [[groupsArray objectAtIndex:n] addObject:[tempGroups objectAtIndex:n]]; } [groupsListOV reloadData]; if(chkprof==1){ [self profileShow:profile_Id]; }else { } [self selectUserInTable:0]; }@catch (NSException * e) { NSRunAlertPanel(@"Error Panel", @"%@", @"OK", nil, nil,e); } } // The method which we are using to frame select query and parse obtained data is: -(void)parseXMLForUser:(int)UId stringVar:(NSString*)stringVar{ @try{ if(queryByPost) [queryByPost release]; queryByPost=[QueryByPost new]; // common class used to invoke method to send request via POST method //obtaining data for xml parsing NSString *query=[NSString stringWithFormat:@"Select * from userinfo update_time = '%@' AND NOT owner_id ='%d' ",stringVar,UId]; NSData *obtainedData=[queryByPost executeQuery:query WithAction:@"query"]; // method invoked to perform post query if(obtainedData==nil){ // data not obtained so return return; } // initializing dictionary to be obtained after parsing if(obtainedDictionary) [obtainedDictionary release]; obtainedDictionary=[NSMutableDictionary new]; // xml parsing if (updatedDataParser) // airportsListParser is an NSXMLParser instance variable [updatedDataParser release]; updatedDataParser = [[NSXMLParser alloc] initWithData:obtainedData]; [updatedDataParser setDelegate:self]; [updatedDataParser setShouldResolveExternalEntities:YES]; BOOL success = [updatedDataParser parse]; } @catch (NSException *e) { NSLog(@"wtihin parseXMLForUser- parseXMLForUser:stringVar: - %@",[e description]); } } //The method which will attempt to interact 4 times with server if interaction with it is found to be unsuccessful , is of following form: -(NSData*)executeQuery:(NSString*)query WithAction:(NSString*)doAction{ NSLog(@"within ExecuteQuery:WithAction: Query is: %@ and Action is: %@",query,doAction); NSString *returnResult; @try { NSString *returnResult; NSMutableURLRequest *postRequest; NSError *error; NSData *searchData; NSHTTPURLResponse *response; postRequest=[self directMySQLQuery:query WithAction:doAction]; // this method sends actual POST request NSLog(@"after directMYSQL in QueryByPost- performQuery... ErrorLogMsg"); searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; returnResult = [[NSString alloc] initWithData:searchData encoding:NSASCIIStringEncoding]; NSString *resultToBeCompared=[returnResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSLog(@"result obtained - %@/ resultToBeCompared - %@",returnResult,resultToBeCompared); if(![resultToBeCompared isEqualToString:@""]){ }else { sleep(10); postRequest=[self directMySQLQuery:query WithAction:doAction]; searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; if(![resultToBeCompared isEqualToString:@""]){ }else { sleep(10); postRequest=[self directMySQLQuery:query WithAction:doAction]; searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; if(![resultToBeCompared isEqualToString:@""]){ }else { sleep(10); postRequest=[self directMySQLQuery:query WithAction:doAction]; searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; if(![resultToBeCompared isEqualToString:@""]){ }else { sleep(10); postRequest=[self directMySQLQuery:query WithAction:doAction]; searchData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&response error:&error]; if(![resultToBeCompared isEqualToString:@""]){ }else { return nil; } } } } } returnResult = [[NSString alloc] initWithData:searchData encoding:NSASCIIStringEncoding]; return searchData; } @catch (NSException * e) { NSLog(@"within QueryByPost , execurteQuery:WithAction - %@",[e description]); return nil; } } // The method which sends POST request to server , is of following form: -(NSMutableURLRequest *)directMySQLQuery:(NSString*)query WithAction:(NSString*)doAction{ @try{ NSLog(@"Query is: %@ and Action is: %@",query,doAction); // some pre initialization NSString *stringBoundary,*contentType; NSURL *cgiUrl ; NSMutableURLRequest *postRequest; NSMutableData *postBody; NSString *ans=@"434"; cgiUrl = [NSURL URLWithString:@"http://keysoftwareservices.com/API.php"]; postRequest = [NSMutableURLRequest requestWithURL:cgiUrl]; [postRequest setHTTPMethod:@"POST"]; stringBoundary = [NSString stringWithString:@"0000ABCQueryxxxxxx"]; contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", stringBoundary]; [postRequest addValue:contentType forHTTPHeaderField: @"Content-Type"]; //setting up the body: postBody = [NSMutableData data]; [postBody appendData:[[NSString stringWithFormat:@"\r\n\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"code\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:ans] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"action\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:doAction] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"devmode\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"devmode"]] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"q\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithString:query] dataUsingEncoding:NSUTF8StringEncoding]]; [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postRequest setHTTPBody:postBody]; NSLog(@"Direct My SQL ok");// Some time application crashes afte this log //Some time application crashes after "Direct My SQL ok" log return [postRequest mutableCopy]; }@catch (NSException * e) { NSLog(@"NSException %@",e); NSRunAlertPanel(@"Error Panel", @"Within QueryByPost- directMySQLQuery...%@", @"OK", nil, nil,e); return nil; } }

    Read the article

  • How can I successfully dechiper Instruments Messages for iPhone Leak

    - by dubbeat
    Hi, I have a memory leak in my app. (This is the first of many I'm sure :() I've being trying to use Instruments to find it. Instruments gives me a lot of information but I think I must just not know how to use this information. What I did so far was 1) Run the app with Instruments 2) Memory Leak Occurs named general -stack 16 3) Find general - stack 16 in the object allocations part of instruments 4) The information here says the event type is a malloc, that webcore is responsible and the something named WKSetCurrentGraphicContext is the responsible caller. How can I use this given information to discover where in my code the leak is being caused? If I comment out the following function I don't get the leak warning so I guess it should be in there somewhere but I can't see where -(void)constructFeatured { NSString *imageName =[[NSString alloc] initWithFormat:@"%@%@%@",@"http://myweb/avatar_", featuredValueObject.featured_promo_artistid, @".jpg"]; NSURL *url = [NSURL URLWithString:imageName]; CGRect frame; frame.size.width=100; frame.size.height=100; frame.origin.x=20; frame.origin.y=39; [imageName release]; imageName=nil; SDWebImageManager *manager = [SDWebImageManager sharedManager]; UIImage *cachedImage = [manager imageWithURL:url]; if (cachedImage) { cachedImage =[ImageManipulator makeRoundCornerImage:cachedImage : 10 : 10]; UIImageView *avatarimageview = [[UIImageView alloc]initWithImage:cachedImage ]; avatarimageview.frame=frame; [self.view addSubview:avatarimageview]; UIView *spinny = [self.view viewWithTag:SPINNY_TAG]; [spinny removeFromSuperview]; [avatarimageview release]; } else { [manager downloadWithURL:url delegate:self]; } NSURL *url2 =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@",@"http://myweb/", featuredValueObject.featured_promo_artistcountry , @".png"]]; CGRect flagframe; flagframe.size.width=16; flagframe.size.height=11; flagframe.origin.x=130; flagframe.origin.y=40; NSData* data = [[NSData alloc] initWithContentsOfURL:url2]; UIImage* img = [[UIImage alloc] initWithData:data]; UIImageView *imageflagview = [[UIImageView alloc] initWithImage: img]; imageflagview.frame=flagframe; [self.view addSubview:imageflagview]; [imageflagview release]; imageflagview=nil; [data release]; [img release]; [url release]; artistname =[[UILabel alloc]initWithFrame:CGRectMake(130,75, 200, 15)]; [artistname setFont:[UIFont fontWithName:@"Arial" size:(16.0)]]; artistname.backgroundColor= [UIColor clearColor]; artistname.textColor=[UIColor whiteColor]; artistname.text=featuredValueObject.featured_promo_artistname; [self.view addSubview:artistname]; [artistname release]; hasConstructedFeatured=YES; [featuredValueObject release]; featuredValueObject=nil; }

    Read the article

  • UITableView crashes when trying to scroll

    - by Ondrej
    Hi, I have a problem with data in UITableView. I have UIViewController, that contains UITableView outlet and few more things I am using and ... It works :) ... it works lovely, but ... I've created an RSS reader class that is using delegates to deploy the data to the table ... and once again, If I'll just create dummy data in the main controller everything works! problem is with this line: rss.delegate = self; Preview looks a little bit broken than here are those RSS reader files on Google code: (Link to the header file on GoogleCode) (Link to the implementation file on Google code) viewDidLoad function of my controller: IGDataRss20 *rss = [[[IGDataRss20 alloc] init] autorelease]; rss.delegate = self; [rss initWithContentsOfUrl:@"http://rss.cnn.com/rss/cnn_topstories.rss"]; and my delegate methods: - (void)parsingEnded:(NSArray *)result { super.data = [[NSMutableArray alloc] initWithArray:result]; NSLog(@"My Items: %d", [super.data count]); [super.table reloadData]; NSLog(@"Parsing ended"); } (void)parsingError:(NSString *)message { NSLog(@"MyMessage: %@", message); } (void)parsingStarted:(NSXMLParser *)parser { NSLog(@"Parsing started"); } Just to clarify, NSLog(@"Parsing ended"); is being executed and I have 10 items in the array. Ok, here's my RSS reader header file: @class IGDataRss20; @protocol IGDataRss20Delegate @optional (void)parsingStarted:(NSXMLParser *)parser; (void)parsingError:(NSString *)message; (void)parsingEnded:(NSArray *)result; @end @interface IGDataRss20 : NSObject { NSXMLParser *rssParser; NSMutableArray *data; NSMutableDictionary *currentItem; NSString *currentElement; id <IGDataRss20Delegate> delegate; } @property (nonatomic, retain) NSMutableArray *data; @property (nonatomic, assign) id delegate; (void)initWithContentsOfUrl:(NSString *)rssUrl; (void)initWithContentsOfData:(NSData *)inputData; @end And this RSS reader implementation file: #import "IGDataRss20.h" @implementation IGDataRss20 @synthesize data, delegate; (void)initWithContentsOfUrl:(NSString *)rssUrl { self.data = [[NSMutableArray alloc] init]; NSURL *xmlURL = [NSURL URLWithString:rssUrl]; rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL]; [rssParser setDelegate:self]; [rssParser setShouldProcessNamespaces:NO]; [rssParser setShouldReportNamespacePrefixes:NO]; [rssParser setShouldResolveExternalEntities:NO]; [rssParser parse]; } (void)initWithContentsOfData:(NSData *)inputData { self.data = [[NSMutableArray alloc] init]; rssParser = [[NSXMLParser alloc] initWithData:inputData]; [rssParser setDelegate:self]; [rssParser setShouldProcessNamespaces:NO]; [rssParser setShouldReportNamespacePrefixes:NO]; [rssParser setShouldResolveExternalEntities:NO]; [rssParser parse]; } (void)parserDidStartDocument:(NSXMLParser *)parser { [[self delegate] parsingStarted:parser]; } (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError { NSString * errorString = [NSString stringWithFormat:@"Unable to parse RSS feed (Error code %i )", [parseError code]]; NSLog(@"Error parsing XML: %@", errorString); if ([parseError code] == 31) NSLog(@"Error code 31 is usually caused by encoding problem."); [[self delegate] parsingError:errorString]; } (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { currentElement = [elementName copy]; if ([elementName isEqualToString:@"item"]) currentItem = [[NSMutableDictionary alloc] init]; } (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:@"item"]) { [data addObject:(NSDictionary *)[currentItem copy]]; } } (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if (![currentItem objectForKey:currentElement]) [currentItem setObject:[[[NSMutableString alloc] init] autorelease] forKey:currentElement]; [[currentItem objectForKey:currentElement] appendString:string]; } (void)parserDidEndDocument:(NSXMLParser *)parser { //NSLog(@"RSS array has %d items: %@", [data count], data); [[self delegate] parsingEnded:(NSArray *)self.data]; } (void)dealloc { [data, delegate release]; [super dealloc]; } @end Hope someone will be able to help me as I am becoming to be quite desperate, and I thought I am not already such a greenhorn :) Thanks, Ondrej

    Read the article

  • Cocoa Basic HTTP Authentication : Advice Needed..

    - by Kristiaan
    Hello all, im looking to read the contents of a webpage that is secured with a user name and password. this is a mac OS X application NOT an iphone app so most of the things i have read on here or been suggested to read do not seem to work. Also i am a total beginner with Xcode and Obj C i was told to have a look at a website that provided sample code to http auth however so far i have had little luck in getting this working. below is the main code for the button press in my application, there is also another unit called Base64 below that has some code in i had to change to even get it compiling (no idea if what i changed is correct mind you). NSURL *url = [NSURL URLWithString:@"my URL"]; NSString *userName = @"UN"; NSString *password = @"PW"; NSError *myError = nil; // create a plaintext string in the format username:password NSMutableString *loginString = (NSMutableString*)[@"" stringByAppendingFormat:@"%@:%@", userName, password]; // employ the Base64 encoding above to encode the authentication tokens char *encodedLoginData = [base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]]; // create the contents of the header NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", [NSString stringWithCString:encodedLoginData length:strlen(encodedLoginData)]]; //NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", loginString];//[NSString stringWithString:loginString length:strlen(loginString)]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 3]; // add the header to the request. Here's the $$$!!! [request addValue:authHeader forHTTPHeaderField:@"Authorization"]; // perform the reqeust NSURLResponse *response; NSData *data = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &myError]; //*error = myError; // POW, here's the content of the webserver's response. NSString *result = [NSString stringWithCString:[data bytes] length:[data length]]; [myTextView setString:result]; code from the BASE64 file #import "base64.h" static char *alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-"; @implementation Base64 +(char *)encode:(NSData *)plainText { // create an adequately sized buffer for the output. every 3 bytes // become four basically with padding to the next largest integer // divisible by four. char * encodedText = malloc((((([plainText length] % 3) + [plainText length]) / 3) * 4) + 1); char* inputBuffer = malloc([plainText length]); inputBuffer = (char *)[plainText bytes]; int i; int j = 0; // encode, this expands every 3 bytes to 4 for(i = 0; i < [plainText length]; i += 3) { encodedText[j++] = alphabet[(inputBuffer[i] & 0xFC) >> 2]; encodedText[j++] = alphabet[((inputBuffer[i] & 0x03) << 4) | ((inputBuffer[i + 1] & 0xF0) >> 4)]; if(i + 1 >= [plainText length]) // padding encodedText[j++] = '='; else encodedText[j++] = alphabet[((inputBuffer[i + 1] & 0x0F) << 2) | ((inputBuffer[i + 2] & 0xC0) >> 6)]; if(i + 2 >= [plainText length]) // padding encodedText[j++] = '='; else encodedText[j++] = alphabet[inputBuffer[i + 2] & 0x3F]; } // terminate the string encodedText[j] = 0; return encodedText;//outputBuffer; } @end when executing the code it stops on the following line with a EXC_BAD_ACCESS ?!?!? NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", [NSString stringWithCString:encodedLoginData length:strlen(encodedLoginData)]]; any help would be appreciated as i am a little clueless on this problem, not being very literate with Cocoa, objective c, xcode is only adding fuel to this fire for me.

    Read the article

  • How to parse HTML with TouchXML or some other alternative.

    - by 0SX
    Hi, I'm trying to parse the HTML presented below with TouchXML but it keeps crashing when I try to extract certain attributes. I'm totally new to the parser world so I apologize for being a complete idiot. I need help to parse this HTML. What I'm trying to accomplish is to parse each attribute and value or what not and copy them to a string. I've been trying to find a good parser to parse HTML and I believe TouchXML is the best I've seen because of Tidy. Speaking of Tidy, How could I run this HTML through Tidy first then parse it? I'm not sure how to do this. Here is the code that I have so far that doesn't work due to it's not pulling everything I need from the HTML. Any help or advice would be much appreciated. Thanks My current code: NSMutableArray *res = [[NSMutableArray alloc] init]; // using local resource file NSString *XMLPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"example.html"]; NSData *XMLData = [NSData dataWithContentsOfFile:XMLPath]; CXMLDocument *doc = [[[CXMLDocument alloc] initWithData:XMLData options:0 error:nil] autorelease]; NSArray *nodes = NULL; nodes = [doc nodesForXPath:@"//div" error:nil]; for (CXMLElement *node in nodes) { NSMutableDictionary *item = [[NSMutableDictionary alloc] init]; [item setObject:[[node attributeForName:@"id"] stringValue] forKey:@"id"]; [res addObject:item]; [item release]; } NSLog(@"%@", res); [res release]; HTML file that needs to be parsed: <html> <head> <base target="_blank" /> </head> <body style="margin:2;"> <div id="group"> <div id="groupURL"><a href="http://www.example.com/groups">Group URL</a></div> <img id="grouplogo" src="http://images.example.com/groups/image.png" /> <div id="groupcomputer"><a href="http://www.example.com/groups/page" title="Group Title">Group title this would be here</a></div> <div id="groupinfos"> <div id="groupinfo-l">Person</div><div id="groupinfo-r">Ralph</div> <div id="groupinfo-l">Years</div><div id="groupinfo-r">4 years</div> <div id="groupinfo-l">Salary</div><div id="groupinfo-r">100K</div> <div id="groupinfo-l">Other</div><div id="groupoth" style="width:15px">other info</div> </body> </html> EDIT: I could use Element Parser but I need to know how to extract the Person's Name from the following example which would be Ralph in this case. <div id="groupinfo-l">Person</div><div id="groupinfo-r">Ralph</div>

    Read the article

  • NSOperation unable to load data on the TableView

    - by yeohchan
    I have a problem in NSOperation. I tried many ways but it would run behind the screen, but will not make it appear on the my table view. Can anyone help me out with this. I am new to NSOperation. Recents.h #import <UIKit/UIKit.h> #import "FlickrFetcher.h" @interface Recents : UITableViewController { FlickrFetcher *fetcher; NSString *name; NSData *picture; NSString *picName; NSMutableArray *names; NSMutableArray *pics; NSMutableArray *lists; NSArray *namelists; NSOperationQueue *operationQueue; } @property (nonatomic,retain)NSString *name; @property (nonatomic,retain)NSString *picName; @property (nonatomic,retain)NSData *picture; @property (nonatomic,retain)NSMutableArray *names; @property (nonatomic,retain)NSMutableArray *pics; @property(nonatomic,retain)NSMutableArray *lists; @property(nonatomic,retain)NSArray *namelists; @end Recents.m #import "Recents.h" #import "PersonList.h" #import "PhotoDetail.h" @implementation Recents @synthesize picName,picture,name,names,pics,lists,namelists; // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { // Custom initialization self.title=@"Recents"; } return self; } - (void)beginLoadingFlickrData{ NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(synchronousLoadFlickrData) object:nil]; [operationQueue addOperation:operation]; [operation release]; } - (void)synchronousLoadFlickrData{ fetcher=[FlickrFetcher sharedInstance]; NSArray *recents=[fetcher recentGeoTaggedPhotos]; [self performSelectorOnMainThread:@selector(didFinishLoadingFlickrDataWithResults:) withObject:recents waitUntilDone:NO]; } - (void)didFinishLoadingFlickrDataWithResults:(NSArray *)recents{ for(NSDictionary *dic in recents){ [names addObject:[fetcher usernameForUserID:[dic objectForKey:@"owner"]]]; if([[dic objectForKey:@"title"]isEqualToString:@""]){ [pics addObject:@"Untitled"]; }else{ [pics addObject:[dic objectForKey:@"title"]]; } NSLog(@"OK!!"); } [self.tableView reloadData]; [self.tableView flashScrollIndicators]; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; operationQueue = [[NSOperationQueue alloc] init]; [operationQueue setMaxConcurrentOperationCount:1]; [self beginLoadingFlickrData]; self.tableView.rowHeight = 95; } /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (void)dealloc { [super dealloc]; } #pragma mark - #pragma mark Table View Data Source Methods - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return[names count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:SimpleTableIdentifier] autorelease]; } cell.detailTextLabel.text=[names objectAtIndex:indexPath.row]; cell.textLabel.text=[pics objectAtIndex:indexPath.row]; //UIImage *image=[UIImage imageWithData:[self.lists objectAtIndex:indexPath.row]]; //cell.imageView.image=image; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { fetcher=[[FlickrFetcher alloc]init]; PhotoDetail *scroll=[[PhotoDetail alloc]initWithNibName:@"PhotoDetail" bundle:nil]; scroll.titleName=[self.pics objectAtIndex:indexPath.row]; scroll.picture = [UIImage imageWithData:[self.lists objectAtIndex:indexPath.row]]; [self.navigationController pushViewController:scroll animated:YES]; }

    Read the article

  • Iphone sdk, How to post data to web server? anybody has example ?

    - by user352385
    Hi, guys, I want to post data to web server, like username and password, on the web server, I used PHP to echo yes or no, I attached all the code. Can anybody help me out, what is wrong with the code. Since it always says incorrect password or username. I tried to test the php code with username and password inside, it is working. So please help me. Thank you. Header file @interface kiksyloginViewController : UIViewController { IBOutlet UITextField *usernameField; IBOutlet UITextField *passwordField; IBOutlet UIButton *loginButton; } @property (nonatomic, retain) UITextField *usernameField; @property (nonatomic, retain) UITextField *passwordField; @property (nonatomic, retain) UIButton *loginButton; (IBAction) login: (id) sender; @end Implementation file #import "kiksyloginViewController.h" @implementation kiksyloginViewController @synthesize usernameField; @synthesize passwordField; @synthesize loginButton; (IBAction) login: (id) sender { NSString *post =[NSString stringWithFormat:@"username=%@&password=%@",usernameField.text, passwordField.text]; NSString *hostStr = @"http://localhost/userlogin.php"; hostStr = [hostStr stringByAppendingString:post]; NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]]; NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding]; if([serverOutput isEqualToString:@"Yes"]){ UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Congrats" message:@"You are authorized " delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alertsuccess show]; [alertsuccess release]; } else { UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Username or Password Incorrect" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alertsuccess show]; [alertsuccess release]; } } (void)didReceiveMemoryWarning { // Releases the view if it doesn’t have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren’t in use. } (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } (void)dealloc { [super dealloc]; } @end PHP file <?php //$Container = new Container ; $u = $_GET['username']; $pw =$_GET['password']; $check = "select username, password from user where username='$u' and password='$pw'"; function myDbconn() { mysql_connect("localhost", "root","") or die(); mysql_select_db("test") or die (mysql_error()); } myDbconn(); $login = mysql_query($check) or die (mysql_error()); //$run = DB()-select($check); if (mysql_num_rows($login)==1){ //$row = DB()-fetch($run); //$row = DB()-fetch($login); $row = mysql_fetch_assoc($login); echo 'yes'; exit; } else { echo 'No'; exit; } ?

    Read the article

  • Cant bind data to a table view

    - by sudhakarilla
    Hi, I have retrieved data from Json URL and displayed it in a table view. I have also inlcuced a button in table view. On clicking the button the data must be transferred to a another table view. The problem is that i could send the data to a view and could display it on a label. But i couldnt bind the dat to table view ... Here's some of the code snippets... Buy Button... -(IBAction)Buybutton{ /* UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"thank u" message:@"products" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil]; [alert show]; [alert release];*/ Product *selectedProduct = [[data products]objectAtIndex:0]; CartViewController *cartviewcontroller = [[[CartViewController alloc] initWithNibName:@"CartViewController" bundle:nil]autorelease]; cartviewcontroller.product= selectedProduct; //NSString *productname=[product ProductName]; //[currentproducts setproduct:productname]; [self.view addSubview:cartviewcontroller.view]; } CartView... // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; data = [GlobalData SharedData]; NSMutableArray *prod =[[NSMutableArray alloc]init]; prod = [data products]; for(NSDictionary *product in prod) { Cart *myprod = [[Cart alloc]init]; myprod.Description = [product Description]; myprod.ProductImage =[product ProductImage]; myprod.ProductName = [product ProductName]; myprod.SalePrice = [product SalePrice]; [data.carts addObject:myprod]; [myprod release]; } Cart *cart = [[data carts]objectAtIndex:0]; NSString *productname=[cart ProductName]; self.label.text =productname; NSLog(@"carts"); } (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [data.carts count]; } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 75; } (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"cellforrow"); static NSString *CellIdentifier = @"Cell"; ProductCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(cell ==nil) { cell = [[[ProductCell alloc]initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]autorelease]; } NSUInteger row = [indexPath row]; Cart *cart = [[data carts]objectAtIndex:row]; cell.productNameLabel.text = [cart ProductName]; /*NSString *sale = [[NSString alloc]initWithFormat:@"SalePrice:%@",[cart SalePrice]]; cell.salePriceLabel.text = sale; cell.DescriptionLabel.text = [cart Description]; NSMutableString imageUrl =[NSMutableString string]; [imageUrl appendFormat:@"http://demo.s2commerce.net/DesktopModules/S2Commerce/Images/Products/%@",[product ProductImage]]; NSLog(@"imageurl:%@",imageUrl); NSString mapURL = [imageUrl stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; NSData* imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mapURL]]; UIImage* image = [[UIImage alloc]initWithData:imageData]; cell.productImageview.image = image; [imageData release]; [image release];*/ return cell; } I am also getting the following error in the console 2010-06-11 18:34:29.169 navigation[4109:207] * -[CartViewController tableView:numberOfRowsInSection:]: message sent to deallocated instance 0xcb4d4f90

    Read the article

  • upload video to youtube via iphone application ----ServiceForbiddenException

    - by user577670
    Hey,I use GData try to upload my video to youtube, but meet these error: serviceBase:<GDataServiceGoogleYouTube: 0x2435f0> objectFetcher:<GDataHTTPUploadFetcher: 0x26dca0> failedWithStatus:403 data:<errors xmlns='http://schemas.google.com/g/2005'> <error> <domain>GData</domain> <code>ServiceForbiddenException</code> <internalReason>Currently authenticated user does not have write access to desrender&apos;s videos.</internalReason> </error> </errors> * is my youtube account. Following is the code: - (GDataServiceGoogleYouTube *)youTubeService { static GDataServiceGoogleYouTube* service = nil; if (!service) { service = [[GDataServiceGoogleYouTube alloc] init]; [service setShouldCacheDatedData:YES]; [service setServiceShouldFollowNextLinks:YES]; [service setIsServiceRetryEnabled:YES]; } // update the username/password each time the service is requested NSString *username = [mUsernameField text]; NSString *password = [mPasswordField text]; if ([username length] > 0 && [password length] > 0) { [service setUserCredentialsWithUsername:username password:password]; } else { // fetch unauthenticated [service setUserCredentialsWithUsername:nil password:nil]; } NSString *devKey = [mDeveloperKeyField text]; [service setYouTubeDeveloperKey:devKey]; return service; } - (IBAction)uploadPressed:(id)sender { NSString *devKey = [mDeveloperKeyField text]; GDataServiceGoogleYouTube *service = [self youTubeService]; [service setYouTubeDeveloperKey:devKey]; NSString *username = [mUsernameField text]; NSString *clientID = [mClientIDField text]; NSURL *url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:username clientID:clientID]; // load the file data NSString *path = [[NSBundle mainBundle] pathForResource:@"YouTubeTest" ofType:@"m4v"]; NSData *data = [NSData dataWithContentsOfFile:path]; NSString *filename = [path lastPathComponent]; // gather all the metadata needed for the mediaGroup NSString *titleStr = [mTitleField text]; GDataMediaTitle *title = [GDataMediaTitle textConstructWithString:titleStr]; NSString *categoryStr = [mCategoryField text]; GDataMediaCategory *category = [GDataMediaCategory mediaCategoryWithString:categoryStr]; [category setScheme:kGDataSchemeYouTubeCategory]; NSString *descStr = [mDescriptionField text]; GDataMediaDescription *desc = [GDataMediaDescription textConstructWithString:descStr]; NSString *keywordsStr = [mKeywordsField text]; GDataMediaKeywords *keywords = [GDataMediaKeywords keywordsWithString:keywordsStr]; BOOL isPrivate = mIsPrivate; GDataYouTubeMediaGroup *mediaGroup = [GDataYouTubeMediaGroup mediaGroup]; [mediaGroup setMediaTitle:title]; [mediaGroup setMediaDescription:desc]; [mediaGroup addMediaCategory:category]; [mediaGroup setMediaKeywords:keywords]; [mediaGroup setIsPrivate:isPrivate]; NSString *mimeType = [GDataUtilities MIMETypeForFileAtPath:path defaultMIMEType:@"video/mp4"]; // create the upload entry with the mediaGroup and the file data GDataEntryYouTubeUpload *entry; entry = [GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup data:data MIMEType:mimeType slug:filename]; SEL progressSel = @selector(ticket:hasDeliveredByteCount:ofTotalByteCount:); [service setServiceUploadProgressSelector:progressSel]; GDataServiceTicket *ticket; ticket = [service fetchEntryByInsertingEntry:entry forFeedURL:url delegate:self didFinishSelector:@selector(uploadTicket:finishedWithEntry:error:)]; [self setUploadTicket:ticket]; } It almost same as GData's YouTubeSample.. Someone help me!!!!

    Read the article

  • Received memory warning on setimage

    - by Sam Budda
    This problem has completely stumped me. This is for iOS 5.0 with Xcode 4.2 What's going on is that in my app I let user select images from their photo album and I save those images to apps document directory. Pretty straight forward. What I do then is that in one of the viewController.m files I create multiple UIImageViews and I then set the image for the image view from one of the picture that user selected from apps dir. The problem is that after a certain number of UIImage sets I receive a "Received memory warning". It usually happens when there are 10 pictures. If lets say user selected 11 pictures then the app crashes with Error (GBC). NOTE: each of these images are at least 2.5 MB a piece. After hours of testing I finally narrowed down the problem to this line of code [button1AImgVw setImage:image]; If I comment out that code. All compiles fine and no memory errors happen. But if I don't comment out that code I receive memory errors and eventually a crash. Also note it does process the whole CreateViews IBAction but still crashes at the end. I cannot do release or dealloc since I am running this on iOS 5.0 with Xcode 4.2 Here is the code that I used. Can anyone tell me what did I do wrong? - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self CreateViews]; } -(IBAction) CreateViews { paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask ,YES); documentsPath = [paths objectAtIndex:0]; //here 15 is for testing purposes for (int i = 0; i < 15; i++) { //Lets not get bogged down here. The problem is not here UIImageView *button1AImgVw = [[UIImageView alloc] initWithFrame:CGRectMake(10*i, 10, 10, 10)]; [self.view addSubview:button1AImgVw]; NSMutableString *picStr1a = [[NSMutableString alloc] init]; NSString *dataFile1a = [[NSString alloc] init]; picStr1a = [NSMutableString stringWithFormat:@"%d.jpg", i]; dataFile1a = [documentsPath stringByAppendingPathComponent:picStr1a]; NSData *potraitImgData1a =[[NSData alloc] initWithContentsOfFile:dataFile1a]; UIImage *image = [[UIImage alloc] initWithData:potraitImgData1a]; // This is causing my app to crash if I load more than 10 images! //[button1AImgVw setImage:image]; } NSLog(@"It went to END!"); } //Error I get when 10 images are selected. App does launch and work 2012-10-07 17:12:51.483 ABC-APP[7548:707] It went to END! 2012-10-07 17:12:51.483 ABC-APP [7531:707] Received memory warning. //App crashes with this error when there are 11 images 2012-10-07 17:30:26.339 ABC-APP[7548:707] It went to END! (gdb)

    Read the article

  • making an array controller the target of a button

    - by ian
    I am working through a chapter of COCOA PROGRAMMING FOR MAC OS X (3RD EDITION) on NSArrayController and it tells me to: Control-Drag to make the array controller become the target of the Add New Employee button. Set the action to add: However when I drag over the array controller it does not highlight so I get no target options. How do I do this correctly in the new XCode full size image document.h: // // Document.h // RaiseMan // // Created by user on 11/12/11. // Copyright (c) 2011 __MyCompanyName__. All rights reserved. // #import <Cocoa/Cocoa.h> @interface Document : NSDocument { NSMutableArray *employees; } @end document.m: // // Document.m // RaiseMan // // Created by user on 11/12/11. // Copyright (c) 2011 __MyCompanyName__. All rights reserved. // #import "Document.h" @implementation Document - (id)init { self = [super init]; if (self) { employees = [[NSMutableArray alloc] init]; } return self; } - (void)dealloc { [self setEmployees:nil]; [super dealloc]; } -(void)setEmployees:(NSMutableArray *)a { //this is an unusual setter method we are goign to ad a lot of smarts in the next chapter if (a == employees) return; [a retain]; [employees release]; employees = a; } - (NSString *)windowNibName { // Override returning the nib file name of the document // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead. return @"Document"; } - (void)windowControllerDidLoadNib:(NSWindowController *)aController { [super windowControllerDidLoadNib:aController]; // Add any code here that needs to be executed once the windowController has loaded the document's window. } - (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError { /* Insert code here to write your document to data of the specified type. If outError != NULL, ensure that you create and set an appropriate error when returning nil. You can also choose to override -fileWrapperOfType:error:, -writeToURL:ofType:error:, or -writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead. */ NSException *exception = [NSException exceptionWithName:@"UnimplementedMethod" reason:[NSString stringWithFormat:@"%@ is unimplemented", NSStringFromSelector(_cmd)] userInfo:nil]; @throw exception; return nil; } - (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError { /* Insert code here to read your document from the given data of the specified type. If outError != NULL, ensure that you create and set an appropriate error when returning NO. You can also choose to override -readFromFileWrapper:ofType:error: or -readFromURL:ofType:error: instead. If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded. */ NSException *exception = [NSException exceptionWithName:@"UnimplementedMethod" reason:[NSString stringWithFormat:@"%@ is unimplemented", NSStringFromSelector(_cmd)] userInfo:nil]; @throw exception; return YES; } + (BOOL)autosavesInPlace { return YES; } - (void)setEmployees:(NSMutableArray *)a; @end person.h: // // Person.h // RaiseMan // // Created by user on 11/12/11. // Copyright (c) 2011 __MyCompanyName__. All rights reserved. // #import <Foundation/Foundation.h> @interface Person : NSObject { NSString *personName; float expectedRaise; } @property (readwrite, copy) NSString *personName; @property (readwrite) float expectedRaise; @end person.m: // // Person.m // RaiseMan // // Created by user on 11/12/11. // Copyright (c) 2011 __MyCompanyName__. All rights reserved. // #import "Person.h" @implementation Person - (id) init { self = [super init]; expectedRaise = 5.0; personName = @"New Person"; return self; } - (void)dealloc { [personName release]; [super dealloc]; } @synthesize personName; @synthesize expectedRaise; @end

    Read the article

  • failed to find PDF header: '%PDF' not found in xCode

    - by Alexander
    I'm trying to create a PDF Object from binary XString in xCode. (OData from SAP, utf-8) Here is the coding: const char* buf = [temp1 UTF8String]; pdffile = [NSData dataWithBytes:buf length:length1]; [webDisplay loadData:self.pdffile MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:nil]; self.webDisplay.scalesPageToFit = YES; temp1 is a XString length1 is the length of PDF file in bytes. I get following error message: failed to find PDF header: '%PDF' not found Some ideas? Thanks!

    Read the article

  • iPhone - UIImage Leak, CGBitmapContextCreateImage Leak

    - by bbullis21
    Alright I am having a world of difficulty tracking down this memory leak. When running this script I do not see any memory leaking, but my objectalloc is climbing. Instruments points to CGBitmapContextCreateImage create_bitmap_data_provider malloc, this takes up 60% of my objectalloc. This code is called several times with a NSTimer. //GET IMAGE FROM RESOURCE DIR NSString * fileLocation = [[NSBundle mainBundle] pathForResource:imgMain ofType:@"jpg"]; NSData * imageData = [NSData dataWithContentsOfFile:fileLocation]; UIImage * blurMe = [UIImage imageWithData:imageData]; NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; UIImage * scaledImage = [blurMe _imageScaledToSize:CGSizeMake(blurMe.size.width / dblBlurLevel, blurMe.size.width / dblBlurLevel) interpolationQuality:3.0]; UIImage * labelImage = [scaledImage _imageScaledToSize:blurMe.size interpolationQuality:3.0]; UIImage * imageCopy = [[UIImage alloc] initWithCGImage:labelImage.CGImage]; [pool drain]; // deallocates scaledImage and labelImage imgView.image = imageCopy; [imageCopy release]; Below is the blur function. I believe the objectalloc issue is located in here. Maybe I just need a pair of fresh eyes. Would be great if someone could figure this out. Sorry it is kind of long... I'll try and shorten it. @implementation UIImage(Blur) - (UIImage *)blurredCopy:(int)pixelRadius { //VARS unsigned char *srcData, *destData, *finalData; CGContextRef context = NULL; CGColorSpaceRef colorSpace; void * bitmapData; int bitmapByteCount; int bitmapBytesPerRow; //IMAGE SIZE size_t pixelsWide = CGImageGetWidth(self.CGImage); size_t pixelsHigh = CGImageGetHeight(self.CGImage); bitmapBytesPerRow = (pixelsWide * 4); bitmapByteCount = (bitmapBytesPerRow * pixelsHigh); colorSpace = CGColorSpaceCreateDeviceRGB(); if (colorSpace == NULL) { return NULL; } bitmapData = malloc( bitmapByteCount ); if (bitmapData == NULL) { CGColorSpaceRelease( colorSpace ); } context = CGBitmapContextCreate (bitmapData, pixelsWide, pixelsHigh, 8, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedFirst ); if (context == NULL) { free (bitmapData); } CGColorSpaceRelease( colorSpace ); free (bitmapData); if (context == NULL) { return NULL; } //PREPARE BLUR size_t width = CGBitmapContextGetWidth(context); size_t height = CGBitmapContextGetHeight(context); size_t bpr = CGBitmapContextGetBytesPerRow(context); size_t bpp = (CGBitmapContextGetBitsPerPixel(context) / 8); CGRect rect = {{0,0},{width,height}}; CGContextDrawImage(context, rect, self.CGImage); // Now we can get a pointer to the image data associated with the bitmap // context. srcData = (unsigned char *)CGBitmapContextGetData (context); if (srcData != NULL) { size_t dataSize = bpr * height; finalData = malloc(dataSize); destData = malloc(dataSize); memcpy(finalData, srcData, dataSize); memcpy(destData, srcData, dataSize); int sums[5]; int i, x, y, k; int gauss_sum=0; int radius = pixelRadius * 2 + 1; int *gauss_fact = malloc(radius * sizeof(int)); for (i = 0; i < pixelRadius; i++) { .....blah blah blah... THIS IS JUST LONG CODE THE CREATES INT FIGURES ........blah blah blah...... } if (gauss_fact) { free(gauss_fact); } } size_t bitmapByteCount2 = bpr * height; //CREATE DATA PROVIDER CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, srcData, bitmapByteCount2, NULL); //CREATE IMAGE CGImageRef cgImage = CGImageCreate( width, height, CGBitmapContextGetBitsPerComponent(context), CGBitmapContextGetBitsPerPixel(context), CGBitmapContextGetBytesPerRow(context), CGBitmapContextGetColorSpace(context), CGBitmapContextGetBitmapInfo(context), dataProvider, NULL, true, kCGRenderingIntentDefault ); //RELEASE INFORMATION CGDataProviderRelease(dataProvider); CGContextRelease(context); if (destData) { free(destData); } if (finalData) { free(finalData); } if (srcData) { free(srcData); } UIImage *retUIImage = [UIImage imageWithCGImage:cgImage]; CGImageRelease(cgImage); return retUIImage; } The only thing I can think of that is holding up the objectalloc is this UIImage *retUIImage = [UIImage imageWithCGImage:cgImage];...but how to do I release that after it has been returned? Hopefully someone can help please.

    Read the article

  • Resizing an image with stretchableImageWithLeftCapWidth

    - by Stephan Burlot
    I'm trying to resize an image using stretchableImageWithLeftCapWidth: it works on the simulator, but on the device, vertical green bars appears. I've tried to use imageNamed, imageWithContentOfFile and imageWithData lo load the image, it doesnt change. UIImage *bottomImage = [[UIImage imageWithData: [NSData dataWithContentsOfFile: [NSString stringWithFormat:@"%@/bottom_part.png", [[NSBundle mainBundle] resourcePath]]]] stretchableImageWithLeftCapWidth:27 topCapHeight:9]; UIImageView *bottomView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 200+73, 100, 73)]; [self.view addSubview:bottomView]; UIGraphicsBeginImageContext(CGSizeMake(100, 73)); [bottomImage drawInRect:CGRectMake(0, 0, 100, 73)]; UIImage *bottomResizedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); bottomView.image = bottomResizedImage; See the result: the green bars shouldn't be there, they dont appear on the simulator.

    Read the article

  • Parsing ISO-8859-1 w/ NSXmlParser

    - by Travis
    I am usin the nsxmlparser and am wondering how I can parse ISO-8859-1 correctly into an NSString. Currently, I am getting results w/ Â for two-byte characters. The XML I'm using (not created by me) starts with <?xml version="1.0" encoding="ISO-8859-1"?> Here are the basic calls I'm using (omitted the NSThread calls). NSString *xmlFilePath = [[NSBundle mainBundle] pathForResource:sampleFileName ofType:@"xml"]; NSString *xmlFileContents = [NSString stringWithContentsOfFile:xmlFilePath encoding:NSUTF8StringEncoding error:nil]; NSData *data = [xmlFileContents dataUsingEncoding:NSUTF8StringEncoding]; NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; [parser setDelegate:self]; [parser parse];

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >