Search Results

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

Page 9/20 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • HTTP POST to Imageshack

    - by Brandon Schlenker
    I am currently uploading images to my server via HTTP POST. Everything works fine using the code below. NSString *UDID = md5([UIDevice currentDevice].uniqueIdentifier); NSString *filename = [NSString stringWithFormat:@"%@-%@", UDID, [NSDate date]]; NSString *urlString = @"http://taptation.com/stationary_data/index.php"; request= [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSString *boundary = @"---------------------------14737809831466499882746641449"; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; NSMutableData *postbody = [NSMutableData data]; [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[NSData dataWithData:imageData]]; [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:postbody]; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog(returnString); However, when I try to convert this to work with Image Shacks XML API, it doesn't return anything. The directions from ImageShack are below. Send the following variables via POST to imageshack. us /index.php fileupload; (the image) xml = "yes"; (specifies the return of XML) cookie; (registration code, optional) Does anyone know where I should go from here?

    Read the article

  • How to encrypt an NSString in Objective C with DES in ECB-Mode?

    - by blauesocke
    Hi, I am trying to encrypt an NSString in Objective C on the iPhone. At least I wan't to get a string like "TmsbDaNG64lI8wC6NLhXOGvfu2IjLGuEwc0CzoSHnrs=" when I encode "us=foo;pw=bar;pwAlg=false;" by using this key: "testtest". My problem for now is, that CCCrypt always returns "4300 - Parameter error" and I have no more idea why. This is my code (the result of 5 hours google and try'n'error): NSString *token = @"us=foo;pw=bar;pwAlg=false;"; NSString *key = @"testtest"; const void *vplainText; size_t plainTextBufferSize; plainTextBufferSize = [token length]; vplainText = (const void *) [token UTF8String]; CCCryptorStatus ccStatus; uint8_t *bufferPtr = NULL; size_t bufferPtrSize = 0; size_t *movedBytes; bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1); bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t)); memset((void *)bufferPtr, 0x0, bufferPtrSize); // memset((void *) iv, 0x0, (size_t) sizeof(iv)); NSString *initVec = @"init Vec"; const void *vkey = (const void *) [key UTF8String]; const void *vinitVec = (const void *) [initVec UTF8String]; ccStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionECBMode, vkey, //"123456789012345678901234", //key kCCKeySizeDES, NULL,// vinitVec, //"init Vec", //iv, vplainText, //"Your Name", //plainText, plainTextBufferSize, (void *)bufferPtr, bufferPtrSize, movedBytes); NSString *result; NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes]; result = [myData base64Encoding];

    Read the article

  • How to call JSON asynchronous in xcode/ iphone develope

    - by Frames84
    I'm using the JSON framework hosting on Google. What and it's a news app that loads JSON feeds, when app goes off to load the feed I want to display the UIActivityIndicatorView but I've found my JSON Access code is not being called asynchronous which is locking the user interface. I have highlighted the function in the code and can't figuree out without breaking how to change the code. #import "JSON DataAccess Wrapper.h" #import "JSON.h" @implementation JSON_DataAccess_Wrapper @synthesize dataItemList; ////////////////////////////////////////////// /* START FEED CONNECTION/ HANDLE METHODS */ ////////////////////////////////////////////// - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [responseData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [responseData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { //label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [connection release]; } - (NSString *)stringWithUrl:(NSURL *)url { NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30]; NSData *urlData; NSURLResponse *response = nil; NSError *error = nil; /* HOW TO MAKE THE CALL BELOW ASYNCHRONOUS */ urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error]; return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]; } -(id) objectWithUrl:(NSURL *)url { SBJSON *jsonParser = [SBJSON new]; NSString *jsonString = [self stringWithUrl:url]; return [jsonParser objectWithString:jsonString error:NULL]; } - (NSMutableArray *) downloadJSONFeed { id response = [self objectWithUrl:[NSURL URLWithString:@"http://www.mysite.co.uk/index2.php?option=JSON"]]; NSMutableArray *feed = (NSMutableArray *) response; return feed; }

    Read the article

  • Obj-msg-send error in numberOfSectionsInTableView

    - by mukeshpawar
    import "AddBillerCategoryViewController.h" import "Globals.h" import "AddBillerViewController.h" import "AddBillerListViewController.h" import"KlinnkAppDelegate.h" @implementation AddBillerCategoryViewController @synthesize REASON, RESPVAR, currentAttribute,tbldata,strOptions; // This recipe adds a title for each section //Initialize the table view controller with the grouped style (AddBillerCategoryViewController *) init { if (self = [super initWithStyle:UITableViewStyleGrouped]);// self.title = @"Crayon Colors"; return self; } -(void)showBack { [[self navigationController] pushViewController:[[AddBillerViewController alloc] init] animated:YES]; } (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated { if ([viewController isKindOfClass:[AddBillerCategoryViewController class]]) { AddBillerCategoryViewController *controller = (AddBillerCategoryViewController *)viewController; [controller.tbldata reloadData]; } } (void)viewDidLoad { appDelegate = (KlinnkAppDelegate *)[[UIApplication sharedApplication] delegate]; appDelegate.catListArray.count; // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; //self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] // initWithTitle:@"Back" // style:UIBarButtonItemStylePlain // target:self // action:@selector(showBack)] autorelease]; if(gotOK == 0) { //self.navigationItem.leftBarButtonItem.enabled = FALSE; dt = [[DateTime alloc] init]; strChannelID = @"IGLOO|MOBILE"; strDateTime = [dt findDateTime]; strTemp = [dt findSessionTime]; strSessionID = [appDelegate.KMobile stringByAppendingString:strTemp]; strResponseURL = @"http://115.113.110.139/Test/CbbpServerRequestHandler"; strResponseVar = @"serverResponseXML"; strRequestType = @"GETCATEGORY"; NSLog(@"Current Session id - %@", strSessionID); //conn = [[NSURLConnection alloc] init]; receivedData = [[NSMutableData data] retain]; //.................... currentAttribute = [[NSMutableString alloc] init]; // create XMl xmlData = [[NSData alloc] init]; xmlData = [self createXML]; // XMl has been created now convert it in to string xmlString = [[NSString alloc] initWithData:xmlData encoding:NSASCIIStringEncoding]; // Ataching other infromatin to he xml parameterString = [[NSString alloc] initWithString:@"mobileRequestXML="]; requestString = [[NSString alloc] init]; requestString = [parameterString stringByAppendingString:xmlString]; // give space betn two element. requestString = [requestString stringByReplacingOccurrencesOfString:@"<" withString:@" <"]; // Initalizing other parameters postData = [requestString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; postLength = [NSString stringWithFormat:@"%d",[postData length]]; firstRequest = [[[NSMutableURLRequest alloc] init] autorelease]; REASON = [[NSMutableString alloc] init]; RESPVAR = [[NSMutableString alloc] init]; NSLog(@"\n \n Sending for 1st time........\n"); [self sendRequest]; NSLog(@"\n \n Sending for 2nd time........\n"); [self sendRequest]; NSLog(@"\n \n both request send........\n \n "); } //[tbldata reloadData]; [self retain]; [super viewDidLoad]; } -(void)sendRequest { finished = FALSE; NSLog(@"\n Sending Request \n\n %@", requestString); conn = [[NSURLConnection alloc] init]; if(gotOK == 0) [firstRequest setURL:[NSURL URLWithString:@"http://115.113.110.139/Test/CbbpMobileRequestHandler"]]; if(gotOK == 1) { [firstRequest setURL:[NSURL URLWithString:@"http://115.113.110.139//secure"]]; gotOK = 2; } [firstRequest setHTTPMethod:@"POST"]; [firstRequest setValue:postLength forHTTPHeaderField:@"Content-Length"]; [firstRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [firstRequest setHTTPBody:postData]; conn = [conn initWithRequest:firstRequest delegate:self startImmediately:YES]; [conn start]; while(!finished) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; } if (conn) { //receivedData = [[NSMutableData data] retain]; NSLog(@"\n\n Received %d bytes of data",[receivedData length]); } else { NSLog(@"\n Not responding"); } } (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@" \n Send didReciveResponse"); [receivedData setLength:0]; } (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@" \n Send didReciveData"); [receivedData appendData:data]; } (void)connectionDidFinishLoading:(NSURLConnection *)connection { finished = TRUE; NSLog(@" \n Send didFinishLaunching"); // do something with the data // receivedData is declared as a method instance elsewhere NSLog(@"\n\n Succeeded! DIDFINISH Received %d bytes of data\n\n ",[receivedData length]); NSString *aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding]; NSLog(aStr); //[conn release]; if([aStr isEqualToString:@"OK"]) gotOK = 1; NSLog(@" Value of gotOK - %d", gotOK); if(gotOK == 2) { responseData = [aStr dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; parser = [[NSXMLParser alloc] initWithData:responseData]; [parser setDelegate:self]; NSLog(@"\n start parsing"); [parser parse]; NSLog(@"\n PArsing over"); NSLog(@"\n check U / S and the RESVAR is - %@",RESPVAR); NSRange textRange; textRange =[aStr rangeOfString:@"<"]; if(textRange.location != NSNotFound) { if([RESPVAR isEqualToString:@"U"]) { self.navigationItem.rightBarButtonItem.enabled = TRUE; self.navigationItem.leftBarButtonItem.enabled = TRUE; NSLog(@" \n U......."); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:REASON delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; [alert show]; [alert release]; } if([RESPVAR isEqualToString:@"S"]) { NSLog(@"\n S........"); [[self navigationController] pushViewController:[[AddBillerCategoryViewController alloc] init] animated:YES]; //[self viewDidLoad]; //[tbldata reloadData]; } } else { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection Problem" message:@"Enable to process your request at this time. Please try again." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; [alert show]; [alert release]; //self.navigationItem.leftBarButtonItem.enabled = TRUE; } } NSLog(@"\n Last line of connectionDidFinish "); //[tableView reloadData]; } -(NSData *)createXML { NSString *strXmlNode = @" channel alliaceid session reqtype responseurl responsevar "; NSString *tempchannel = [strXmlNode stringByReplacingOccurrencesOfString:@"channel" withString:strChannelID options:NSBackwardsSearch range:NSMakeRange(0, [strXmlNode length])]; NSString *tempalliance = [tempchannel stringByReplacingOccurrencesOfString:@"alliaceid" withString:@"WALLET365" options:NSBackwardsSearch range:NSMakeRange(0, [tempchannel length])]; NSString *tempsession = [tempalliance stringByReplacingOccurrencesOfString:@"session" withString:strSessionID options:NSBackwardsSearch range:NSMakeRange(0, [tempalliance length])]; NSString *tempreqtype = [tempsession stringByReplacingOccurrencesOfString:@"reqtype" withString:strRequestType options:NSBackwardsSearch range:NSMakeRange(0,[tempsession length])]; NSString *tempresponseurl = [tempreqtype stringByReplacingOccurrencesOfString:@"responseurl" withString:strResponseURL options:NSBackwardsSearch range:NSMakeRange(0, [tempreqtype length])]; NSString *tempresponsevar = [tempresponseurl stringByReplacingOccurrencesOfString:@"responsevar" withString:strResponseVar options:NSBackwardsSearch range:NSMakeRange(0,[tempresponseurl length])]; NSData *data= [[NSString stringWithString:tempresponsevar] dataUsingEncoding:NSUTF8StringEncoding]; return data; } (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if([elementName isEqualToString:@"RESPVAL"]) currentAttribute = [NSMutableString string]; if([elementName isEqualToString:@"REASON"]) currentAttribute = [NSMutableString string]; if([elementName isEqualToString:@"COUNT"]) currentAttribute = [NSMutableString string]; if([elementName isEqualToString:@"CATNAME"]) currentAttribute = [NSMutableString string]; } (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if([elementName isEqualToString:@"RESPVAL"]) { [RESPVAR setString:currentAttribute]; //NSLog(@"\n Response VAR - %@", RESPVAR); } if([elementName isEqualToString:@"REASON"]) { [REASON setString:currentAttribute]; //NSLog(@"\n Reason - %@", REASON); } if([elementName isEqualToString:@"COUNT"]) { NSString *temp1 = [[NSString alloc] init]; temp1 = [temp1 stringByAppendingString:currentAttribute]; catCount = [temp1 intValue]; [temp1 release]; //NSLog(@"\n Cat Count - %d", catCount); } if([elementName isEqualToString:@"CATNAME"]) { [appDelegate.catListArray addObject:[NSString stringWithFormat:currentAttribute]]; //NSLog(@"%@", appDelegate.catListArray); } } (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if(self.currentAttribute) [self.currentAttribute setString:string]; } /* (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } */ /* (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } */ /* (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } */ /* (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } */ /* // Override to allow orientations other than the default portrait orientation. (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview // Release anything that's not essential, such as cached data } 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 { KlinnkAppDelegate *appDelegated = (KlinnkAppDelegate *)[[UIApplication sharedApplication] delegate]; return appDelegated.catListArray.count; } // Customize the appearance of table view cells. (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } // Set up the cell... AddBillerCategoryViewController *mbvc = (AddBillerCategoryViewController *)[appDelegate.catListArray objectAtIndex:indexPath.row]; [cell setText:mbvc.strOptions]; return cell; } (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic may go here. Create and push another view controller. // AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil]; // [self.navigationController pushViewController:anotherViewController]; // [anotherViewController release]; gotOK = 0; int j = indexPath.row; appDelegate.catName = [[NSString alloc] init]; appDelegate.catName = [appDelegate.catName stringByAppendingString:[appDelegate.catListArray objectAtIndex:j]]; [[self navigationController] pushViewController:[[AddBillerListViewController alloc] init] animated:YES]; } /* // Override to support conditional editing of the table view. (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } */ /* // Override to support editing the table view. (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { } */ /* // Override to support conditional rearranging of the table view. (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the item to be re-orderable. return YES; } */ (void)dealloc { [REASON release]; [RESPVAR release]; [currentAttribute release]; [tbldata release]; [super dealloc]; } @end In the Above code .. numberOfSectionsInTableView ,i get error of obj-msg-send i have intialize the array catlist and even not released it anywhere still why i am getting this error please help me i am badly stuck' thanks in advacnce

    Read the article

  • iPhone - UIImage imageScaledToSize Memory Issue

    - by bbullis21
    I have done research and tried several times to release the UIImage memory and have been unsuccessful. I saw one other post on the internet where someone else was having this same issue. Everytime imageScaledToSize is called, the ObjectAlloc continues to climb. In the following code I am pulling a local image from my resource directory and resizing it with some blur. Can someone provide some help on how to release the memory of the UIImages called....scaledImage and labelImage. This is the chunk of code where the iPhone Intruments has shown to have the ObjectAlloc build up. This chunk of code is called several times with an NSTimer. //Get local image from inside resource NSString * fileLocation = [[NSBundle mainBundle] pathForResource:imgMain ofType:@"jpg"]; NSData * imageData = [NSData dataWithContentsOfFile:fileLocation]; UIImage * blurMe = [UIImage imageWithData:imageData]; //Resize and blur image 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]; imgView.image = labelImage;

    Read the article

  • AVAudioPlayer only initializes with some files

    - by Brendan
    Hi everyone, I'm having trouble playing some files with AVAudioPlayer. When I try to play a certain m4a, it works fine. It also works with an mp3 that I try. However it fails on one particular mp3 every time (15 Step, by Radiohead), regardless of the order in which I try to play them. The audio just does not play, though the view loading and everything that happens concurrently happens correctly. The code is below. I get the "Player loaded." log output on the other two songs, but not on 15 Step. I know the file path is correct (I have it log outputted earlier in the app, and it is correct). Any ideas? NSData *musicData = [NSData dataWithContentsOfURL:[[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:[song filename] ofType:nil]]]; NSLog([[NSBundle mainBundle] pathForResource:[song filename] ofType:nil]); if(musicData) { NSLog(@"File found."); } self.songView.player = [[AVAudioPlayer alloc] initWithData:musicData error:nil]; if(self.songView.player) { NSLog(@"Player loaded."); } [self.songView.player play]; NSLog(@"You should be hearing something now."); Thanks, Brendan

    Read the article

  • Is This a Valid Way to Use Blocks in Objective-C?

    - by Carter
    I've been building a HTTP client that uses web services to synchronize information between the client and server. I've been using Blocks and NSURLConnection to achieve this on the client side, but I'm getting frequent EXC_BAD_ACCESS crashes in objc_msgSend(). From what I understand, this usually means that a stored block that has fallen off the stack has been called. I think I've coded things correctly to avoid this, but I'm still stuck. Here is conceptually what my code is doing. It starts by calling "synchronizeWithWebServer". That method invokes "listRootObjectsOnServerWithBlock:" which takes in a block to be called when the method returns. "listRootObjectsOnServersWithBlock:" initiates a NSURLConnection to the web server asynchronously. It to expects a block to be called when it returns. Inside that block I want to be able to execute the original Block (so aptly named 'block'). This is only a simplified version of my code. The real synchronization process is more complex but it's mostly more of the same as what you see below. Sometimes the code works perfectly, but about 80% of the time it crashes very early on in the routine. It seems to be more vulnerable to crashing when my data set gets larger. - (void)synchronizeWithWebServer { [self listRootObjectsOnServerWithBlock:^(NSArray *results, NSError *error) { //Iterate over result objects and perform some other similar routines. }]; } - (void)listRootObjectsOnServerWithBlock:(void (^)(NSArray *results, NSError *error))block { //Create NSURLRequest Here //Create connection asynchronously. block = [block copy]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){ //Parse response from web server (stored in NSData *data) NSArray *results = ..... //Call 'block' block(results, error); [block release]; }]; }

    Read the article

  • Printing Pdf using AirPrint causes cut-off content

    - by Jatin Patel
    Here i am printing pdf with size 'pageSize = CGSizeMake(640, 832);'. this size is larget then A4 size page aspected. so i will cut-off some text(means it will not print whole page). while printing same pdf using MAC, it will print whole page with help of option (scale to fit). so can any one help me to come out from this problem.. is there any option in IOS sdk for scale to fit. here is my code.. -(void)printItem { NSArray *aArrPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ; NSString *aStr = [[aArrPaths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"PropertyReport_%d.pdf",self.propertyId]]; // NSString *aStr = [[NSBundle mainBundle] pathForResource:@"TRADUZIONE HELP SECTIONS REV2" ofType:@"pdf"]; NSURL *url=[[NSURL alloc] initFileURLWithPath:aStr]; NSData *data=[[NSData alloc] initWithContentsOfURL:url]; printController = [UIPrintInteractionController sharedPrintController]; if(printController && [UIPrintInteractionController canPrintData:data]) { printController.delegate = self; UIPrintInfo *printInfo = [UIPrintInfo printInfo]; printInfo.outputType = UIPrintInfoOutputGeneral; //printInfo.jobName = [NSString stringWithFormat:@"New Image"]; printInfo.duplex = UIPrintInfoDuplexLongEdge; printController.printInfo = printInfo; printController.showsPageRange = YES; printController.printingItem = data; void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) { if (!completed && error) { //NSLog(@"FAILED! due to error in domain %@ with error code %u", error.domain, error.code); } }; // aWebViewPDF.hidden=FALSE; [printController presentAnimated:YES completionHandler:completionHandler]; } } Thanks Jatin Patel

    Read the article

  • iPhone - UIViewController not rotating when device orientation changes

    - by Ryu
    I have got my own custom UIViewController, which contains a UIScrollView with an UIImageView as it's subview. I would like to make the image to auto rotate when device orientation changes, but it doesn't seem to be working... In the header file, I've got; @interface MyViewController : UIViewController <UIScrollViewDelegate> { IBOutlet UIScrollView *containerView; UIImageView *imageView; } These components are initialised in the loadView function as below; containerView = [[UIScrollView alloc] initWithFrame:frame]; NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://..."]]; UIImage *image = [[UIImage alloc] initWithData:data]; imageView = [[UIImageView alloc] initWithImage:image]; [image release]; [containerView addSubview:imageView]; And I have added the following method, assuming that's all I need to make the view auto-rotate... -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return YES; } MyViewController loads fine with the image I've specified to grab from the URL, and the shouldAutorotate... function is being called, with the correct UIInterfaceOrientation, when I flip the device too. However, didRotateFromInterfaceOrientation method do not get called, and the image doesn't seem to rotate itself... Could someone please point out what I need to add, or what I have done wrong here? Thanks in advance!

    Read the article

  • There is no attachment in the sent mail by iPhone

    - by naruhodo
    I'm trying to send a recorded sound file as attachment with MFMailComposeViewController. The sound file is OK. The picker shows the correct file name, shows the audio file icon as attachment, sends the mail, but there is no attachment in the result. I attached below the source of the sent mail. There is a "text/plain" content type part instead of "Content-Disposition: attachment;" as expected. This is my code code to define the path and attach the audio file. What could be wrong? #define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] #define FILEPATH [DOCUMENTS_FOLDER stringByAppendingPathComponent:[self dateString]] ... NSURL *url = [NSURL fileURLWithPath:FILEPATH]; self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error]; ... MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init]; picker.mailComposeDelegate = self; NSURL *url = [NSURL fileURLWithPath: [NSString stringWithFormat:@"%@", [self.recorder url]]]; NSData *audioData = [NSData dataWithContentsOfFile:[url path]]; [picker addAttachmentData:audioData mimeType:@"audio/wav" fileName:[[url path] lastPathComponent]]; and the source of the sent mail: Content-type: multipart/mixed; boundary=Apple-Mail-1-614960740 Content-transfer-encoding: 7bit MIME-version: 1.0 (iPod Mail 7E18) Subject: Sound message: Date: Sun, 11 Apr 2010 11:58:56 +0200 X-Mailer: iPod Mail (7E18) --Apple-Mail-1-614960740 Content-Type: text/plain;     charset=us-ascii;     format=flowed Content-Transfer-Encoding: 7bit It is a text here --Apple-Mail-1-614960740 Content-Type: text/plain;     charset=us-ascii;     format=flowed Content-Transfer-Encoding: 7bit Sent from my iPod --Apple-Mail-1-614960740--

    Read the article

  • iphone download several files

    - by Floo
    hi all !  In my app i need to download several plist.  to download a plist i use the NSURLconnection  in my code i use an UIAlertView with a UIActivityIndicator then when the download is finished i add a button to the alert to dismiss it.  To download the plist i use somewhere in my code an NSURL set to the adresse where the plist is, next i set a NSURLRequest with the url cache policy and a timeout interval.  Then i set my NSMutableData to the NSURL connection with a NSURLRequest.  In the delegate didReceiveData: i append data to my mutable data object, in the didFailWithError: i handle error. And finaly in the connectionDidFinishLoading  i serialize my data to a plist so i can write to file my plist, and release my alertview.  My problem is : how can i do if i have sevetal file to download because the connectionDidFinishLoading is called each time my NSURLConnection is finished but i want to release my UiAlert when everything is finished. But when the first plist is downloaded my code in the connectionDidFinishLoading will fire.  here is my code :  in the view did load :  // set the UiAlert in the view did load  NSURL *theUrl = [NSURL URLWithString:@"http://adress.com/plist/myPlist.plist"]; NSURLRequest *theRequest = [NSURLRequest requestWithURL:theUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; self.plistConnection = [[ NSURLConnection alloc] initwithRequest:theRequest delegate:self startImmediatly:YES]; //plistConnection is a NSURLConnection - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {  [incomingPListData appendData:data]; } -(void)connection:(NSURLConnection *)connectionDidFailWithError:(NSError *)error { // handle error here  } -(void)connectionDidFinisloading:(NSURLConnection *) connection {  NSPropertyListFormat format; NSString *serialErrorString;  NSData *plist = [NSPropertyListSerialisation propertyListFromData:incomingPlistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&serialErrorString]; if (serialErrorString) {//error} else { // create path and write plist to path} // change message and title of the alert so if i want todownload an another file  where do i put the request the connection and how can i tell the didFinishLoading to fire code when all my file are downloaded.  thanks to all

    Read the article

  • xcode may not respond to warning

    - by Frames84
    Hi all, Can't seem to get rid of a warning. The warning is: 'UIImage' may not respond to '-scaleToSize' above the @implmentation MyViewController I have this @implementation: @implementation UIImage (scale) -(UIImage*)scaleToSize:(CGSize)size { UIGraphicsBeginImageContext(size); [self drawInRect:CGRectMake(0, 0, size.width, size.height)]; UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; } @end Then I have MyViewController implementation @implementation TodayNewsTableViewController @synthesize dataList; ...... - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MainNewsCellIdentifier = @"MainNewsCellIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: MainNewsCellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: MainNewsCellIdentifier] autorelease]; } NSUInteger row = [indexPath row]; NSDictionary *stream = (NSDictionary *) [dataList objectAtIndex:row]; NSString *title = [stream valueForKey:@"title"]; if( ! [title isKindOfClass:[NSString class]] ) { cell.textLabel.text = @""; } else { cell.textLabel.text = title; } cell.textLabel.numberOfLines = 2; cell.textLabel.font =[UIFont systemFontOfSize:10]; cell.detailTextLabel.numberOfLines = 1; cell.detailTextLabel.font= [UIFont systemFontOfSize:8]; cell.detailTextLabel.text = [stream valueForKey:@"created"]; NSString *i = [NSString stringWithFormat:@"http://www.mywebsite.co.uk/images/%@", [stream valueForKey:@"image"]]; NSData *imageURL = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:i]]; UIImage *newsImage = [[UIImage alloc] initWithData:imageURL] ; UIImage *scaledImage = [newsImage scaleToSize:CGSizeMake(50.0f, 50.0f)]; // warning is appearing here. cell.imageView.image = scaledImage; [imageURL release]; [newsImage release]; return cell; } Thanks for your time in advance. Frames

    Read the article

  • Multiple Application Support Directories for iPhone Simulator?

    - by Alex G
    I am developing an iPhone app with someone else. The app works fine for me, but he is running into a bug. We think this bug is related to the fact that he is getting multiple Application directories for this same app. In my ~/Library/Application Support/iPhone Simulator/User/Applications, I only have one folder at all times. He says that he will get 3 or 4 directories when he is only working on this one app. We think this is our problem because our bug has to do with displaying images that are stored in the app's Documents folder. Does anyone know why he is ending up with multiple directories or how to stop it? Edit: Here is the code for writing the image to a file: NSData *image = [NSData dataWithContentsOfURL:[NSURL URLWithString:[currentArticle articleImage]]]; NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *imagePath = [array objectAtIndex:0]; NSFileManager *NSFM = [NSFileManager defaultManager]; BOOL isDir = YES; if(![NSFM fileExistsAtPath:imagePath isDirectory:&isDir]) if(![NSFM createDirectoryAtPath:imagePath attributes:nil]) NSLog(@"error"); imagePath = [imagePath stringByAppendingFormat:@"/images"]; if(![NSFM fileExistsAtPath:imagePath isDirectory:&isDir]) if(![NSFM createDirectoryAtPath:imagePath attributes:nil]) NSLog(@"error"); imagePath = [imagePath stringByAppendingFormat:@"/%@.jpg", [currentArticle uniqueID]]; [image writeToFile:imagePath atomically:NO]; And here is the code for getting the path when I need the image: - (NSString *)imagePath { NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *imagePath = [array objectAtIndex:0]; return [imagePath stringByAppendingFormat:@"/images/%@.jpg", [self uniqueID]]; } The app works great for me, but my partner says that the images don't show up intermittently, and he notices that he gets multiple directories in his Applications folder.

    Read the article

  • iPhone: Cell imageViews repeating when loaded from url

    - by araid
    I'm developing a demo RSS reader for iPhone. I obviously have a tableview to display the feeds, and then a detailed view. Some of this feeds have a thumbnail that I want to display on cell.imageview of the table, and some don't. The problem is that when scrolling the table, loaded thumbnails start repeating on other cells, and I end up with a thumbnail on every cell. Here's a piece of my code. I may upload screenshots later - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: @"rssItemCell"]; if(nil == cell){ cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"rssItemCell"]autorelease]; } BlogRss *item = [[[self rssParser]rssItems]objectAtIndex:indexPath.row]; cell.textLabel.text = [item title]; cell.detailTextLabel.text = [item description]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; // Thumbnail if exists if(noticia.imagePath != nil){ NSData* imageData; @try { imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:item.imagePath]]; } @catch (NSException * e) { //Some error while downloading data } @finally { item.image = [[UIImage alloc] initWithData:imageData]; [imageData release]; } } if(item.image != nil){ [[cell imageView] setImage:item.image]; } return cell; } Any help will be very appreciated.

    Read the article

  • Verifying existence of name and password in NSUserDefaults to Skip a login/Screen

    - by Michael Robinson
    I have a Tabbar/Tableview App that modally loads a Login/Signup view when the app loads, I have set up a Root.plist in a settings bundle for the name and password and have successfully retrieved the items. I want to be able to do two things: 1) Do a test to see if the NSUserDefault Strings are empty and if so load the Login/Signup view. 2) If the strings are available then use the string contents to login to my Webservice. Thanks in advance. Here is my LoginViewController .m : @synthesize usernameField; @synthesize passwordField; @synthesize loginButton; @synthesize loginIndicator; @synthesize usernameLabel; @synthesize passwordLabel; -(void)refreshFields { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; usernameLabel.text = [defaults objectForKey:kUsernameKey]; passwordLabel.text = [defaults objectForKey:kPasswordKey]; } - (void)viewDidAppear:(BOOL)animated { [self refreshFields]; [super viewDidAppear:animated]; } - (void)viewDidLoad { [super viewDidLoad]; [self refreshFields]; [self.navigationController setNavigationBarHidden:YES animated:NO]; } - (IBAction) login: (id) sender { { NSString *post =[NSString stringWithFormat:@"username=%@&password=%@",usernameField.text, passwordField.text]; NSString *hostStr = @"http:~iphone_login.php?"; hostStr = [hostStr stringByAppendingString:post]; NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]]; NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding]; NSLog(@"Site: %@",hostStr); NSLog(@"Site: %@",serverOutput); 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];

    Read the article

  • ScrollView content async downloading problem

    - by Newbee
    Hi! I have UIScrollView with lots of UIImageView inside. In the loadView method I assign some temporary image for each of subview UIImageView images and starts several threads to async download images from internet. Each thread downloads and assign images as follows: NSData *data = [NSData dataWithContentsOfURL:URL]; UIImage *img = [UIImage imageWithData:data]; img_view.image = img; Here is the problem - I expects picture will changed after each image downloaded by I can see only temporary images until all images will downloads. UIScrollView still interact while images downloads - I can scroll temporary images inside it and see scrollers and nothing blocks run loop, but downloaded images doesn't updates.. What I tried to do: Call sleep() in the download thread -- not helps. Call setNeedsDisplay for each ImageView inside ScrollView and for ScrollView -- not helps. What's wrong ? Thanks. Update. I tried some experiments with number of threads and number of images to download. Now I'm sure -- images redraws only when thread finished. For example - if I load 100 images with one thread -- picture updates one time after all images downloads. If I increase number of threads to 10 -- picture updates 10 times -- 10 images appears per update. One more update. I fixed problem by staring new thread from the downloading threads each time one image downloaded and exit current thread (instead of download several images in one thread in the cycle and exit thread only when all downloaded). Obviously it's not a good solution and there must be right approach.

    Read the article

  • Send POSTs to a PHP script on a server

    - by Sam Jarman
    I have a PHP script on a server <?php // retrieve POST vars $comment = $_POST['comment']; $email = $_POST['email']; // remove trailing whitespace etc $comment = trim($comment); $email = trim($email); // format date accoring to http://www.w3schools.com/php/func_date_date.asp $date_time = date("Y-m-d-H-i-s"); // i.e. 2010-04-15-09-45-23 // prepare message $to = "(removed my email addy)"; //who to send the mail to $subject = "Feedback from iPhone app"; //what to put in the subject line $message = "Name/Email: $email \r\n Comment: $comment"; mail($to, $subject,$message) or "bad"; echo "ok"; ?> How do I now send a POST request from my iPhone app... ive tried this sort of thing... NSURL *url = [NSURL URLWithString:@"mysite.com/script.php"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; NSString *message = boxForSuggestion.text; NSString *userEmailString = usersEmail.text; NSString *requestBodyString = [NSString stringWithFormat:@"comment:%@&email%@", message , userEmailString]; NSData *requestBody = [requestBodyString dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPMethod:@"POST" [request setHTTPBody:requestBody]; NSURLResponse *response = NULL; NSError *requestError = NULL; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError]; NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease]; NSLog(@"%@", responseString); Any ideas? Thanks guys Sam

    Read the article

  • How to update the user profile through tokenid when a particular user logs in using his username and password

    - by Rani
    i have an application in which when the user enters his username and password in the login form , his username and password are submitted to the server database for validation and if he is a valid user a tokenid is generated for him through JSON response and he is allowed to log in.this is the JSON response that i get in the console when a valid user log in through the log in form : {"TokenID":"kaenn43otO","isError":false,"ErrorMessage":"","Result":[{"UserId":"164","FirstName":"Indu","LastName":"nair","Email":"[email protected]","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"22"}],"ErrorCode":900} 2011-06-24 11:56:57.639 Journey[5526:207] this is token id:kaenn43otO so when the same user wants to update his profile by clicking on the update tab using the tokenid So that if he want he can his firstname,lastname,password,email.etc.i i have done the following code to update the user profile using tokenid but it does not work.i get tokenid when the user log in and this tokenid i have to pass to other class: this is my code to update user profile: -(void)sendRequest { //this is the class in which i get the tokenid and i am passing it to this class apicontroller *apitest = [[apicontroller alloc]init]; NSString *tokentest = apitest.tokenapi; NSString *post = [NSString stringWithFormat:@"Token=%@&firstname=%@&lastname=%@&Username=%@&Password=%@&Email=%@",tokentest,txtfirstName.text,txtlast.text,txtUserName.text,txtPassword.text,txtEmail.text]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSLog(@"%@",postLength); NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:@"http://192.168.0.1:96/JourneyMapperAPI?RequestType=Register&Command=SET"]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (theConnection) { webData = [[NSMutableData data] retain]; NSLog(@"%@",webData); [theConnection start]; } else { } } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [webData setLength: 0]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [webData appendData:data]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [connection release]; [webData release]; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; NSLog(@"%@",loginStatus); [loginStatus release]; [connection release]; [webData release]; } -(IBAction)click:(id)sender { [self sendRequest]; } this is my apicontroller.m file in which i am creating login form so that user login and in this page tokenid is generated -(void)sendRequest { UIDevice *device = [UIDevice currentDevice]; NSString *udid = [device uniqueIdentifier]; //NSString *sysname = [device systemName]; NSString *sysver = [device systemVersion]; NSString *model = [device model]; NSLog(@"idis:%@",[device uniqueIdentifier]); NSLog(@"system nameis :%@",[device systemName]); NSLog(@"System version is:%@",[device systemVersion]); NSLog(@"System model is:%@",[device model]); NSLog(@"device orientation is:%d",[device orientation]); NSString *post = [NSString stringWithFormat:@"Loginkey=%@&Password=%@&DeviceCode=%@&Firmware=%@&IMEI=%@",txtUserName.text,txtPassword.text,model,sysver,udid]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSLog(@"%@",postLength); NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:@"http://192.168.0.1:96/JourneyMapperAPI?RequestType=Login"]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (theConnection) { webData = [[NSMutableData data] retain]; NSLog(@"%@",webData); } else { } } //to select username and password from database. -(void)check { //app.journeyList = [[NSMutableArray alloc]init]; [self createEditableCopyOfDatabaseIfNeeded]; NSString *filePath = [self getWritableDBPath]; sqlite3 *database; if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) { const char *sqlStatement = "SELECT Username,Password FROM UserInformation where Username=? and Password=?"; sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { sqlite3_bind_text(compiledStatement, 1, [txtUserName.text UTF8String], -1, SQLITE_TRANSIENT); sqlite3_bind_text(compiledStatement, 2, [txtPassword.text UTF8String], -1, SQLITE_TRANSIENT); //NSString *loginname= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]; // NSString *loginPassword = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)]; } if(sqlite3_step(compiledStatement) != SQLITE_ROW ) { NSLog( @"Save Error: %s", sqlite3_errmsg(database) ); UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"User is not valid" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; alert = nil; } else { isUserValid = YES; if (isUserValid) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"Valid User" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } } sqlite3_finalize(compiledStatement); } sqlite3_close(database); } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [webData setLength: 0]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [webData appendData:data]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [connection release]; [webData release]; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; NSLog(@"%@",loginStatus); //this is to perfrom insert opertion on the userinformation table NSString *json_string = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding]; NSDictionary *result = [json_string JSONValue]; //here i am storing the tokenid tokenapi = [result objectForKey:@"TokenID"]; NSLog(@"this is token id:%@",tokenapi); // BOOL errortest = [[result objectForKey:@"isError"] boolValue]; if(errortest == FALSE) { values = [result objectForKey:@"Result"]; NSLog(@"Valid User"); } else { NSLog(@"Invalid User"); } NSMutableArray *results = [[NSMutableArray alloc] init]; for (int index = 0; index<[values count]; index++) { NSMutableDictionary * value = [values objectAtIndex:index]; Result * result = [[Result alloc] init]; //through this i get the userid result.UserID = [value objectForKey:@"UserId"]; result.FirstName = [value objectForKey:@"FirstName"]; result.Username =[value objectForKey:@"Username"]; result.Email =[value objectForKey:@"Email"]; result.ProfileImage =[value objectForKey:@"ProfileImage"]; result.ThumbnailImage =[value objectForKey:@"ThumbnailImage"]; result.DeviceInfoId =[value objectForKey:@"DeviceInfoId"]; NSLog(@"%@",result.UserID); [results addObject:result]; [result release]; } for (int index = 0; index<[results count]; index++) { Result * result = [results objectAtIndex:index]; //save the object variables to database here [self createEditableCopyOfDatabaseIfNeeded]; NSString *filePath = [self getWritableDBPath]; sqlite3 *database; if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) { const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,Username,Password,FirstName,Email) VALUES (?,?,?,?,?,?)"; sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { //sqlite3_bind_text( compiledStatement, 1, [journeyid UTF8String],-1,SQLITE_TRANSIENT); sqlite3_bind_text( compiledStatement, 1, [result.UserID UTF8String],-1,SQLITE_TRANSIENT); sqlite3_bind_text(compiledStatement, 2, [result.DeviceInfoId UTF8String],-1,SQLITE_TRANSIENT); sqlite3_bind_text(compiledStatement, 3, [txtUserName.text UTF8String],-1,SQLITE_TRANSIENT); sqlite3_bind_text(compiledStatement, 4, [txtPassword.text UTF8String],-1,SQLITE_TRANSIENT); sqlite3_bind_text (compiledStatement, 5, [result.FirstName UTF8String],-1,SQLITE_TRANSIENT); sqlite3_bind_text (compiledStatement, 6, [result.Email UTF8String],-1,SQLITE_TRANSIENT); } if(sqlite3_step(compiledStatement) != SQLITE_DONE ) { NSLog( @"Save Error: %s", sqlite3_errmsg(database) ); } else { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"Record added" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; alert = nil; } sqlite3_finalize(compiledStatement); } sqlite3_close(database); } [loginStatus release]; [connection release]; [webData release]; } -(IBAction)click:(id)sender { [self sendRequest]; //this is to select username and password from database. [self check]; } for a particular user who logs in only his profile must be update by using tokenid and userid.Please help me in solving this problem.Thanks

    Read the article

  • How can I fix this clang warning: "Object with +0 retain counts returned to caller where +1 (owning)

    - by mipadi
    I have a piece of Objective-C code that looks like the following: - (NSString *)copyData:(NSData *)data { NSString *path = [[[self outputDirectory] stringByAppendingPathComponent:@"archive"] stringByAppendingPathExtension:@"zip"]; NSLog(@"Copying data to %@", path); [data writeToFile:path atomically:NO]; return path; } The code is called from an initializer that looks like this: - (id)initWithData:(NSData *)data { if ((self = [super init]) != nil) { NSString *path = [self copyData:data]; // Line 41 (referenced in warning, shown below) return [self initWithContentsOfFile:path]; } return self; } When running the clang static analyzer, I get the following warnings for the path variable: Potential leak of an object allocated on line 41 and stored into 'path' Object with +0 retain counts returned to caller where +1 (owning) retain count is expected I'm confused. My understanding is that stringByAppendingPathComponent should not return an autoreleased string, so it should have a net retain count of 0. (Obviously I don't want to retain it.) I've tried altering copyData: to return the following, but it didn't get rid of the warning: return [[path retain] autorelease]; So what's the deal with this warning?

    Read the article

  • NSURLConnection and empty post variables

    - by SooDesuNe
    I'm at my wits end with this one, because I've used very similar code in the past, and it worked just fine. The following code results in empty $_POST variables on the server. I verified this with: file_put_contents('log_file_name', "log: ".$word, FILE_APPEND); the only contents of log_file_name was "log: " I then verified the PHP with a simple HTML form. It performed as expected. The Objective-C: NSString *word = "this_word_gets_lost"; NSString *myRequestString = [NSString stringWithFormat:@"word=%@", word]; [self postAsynchronousPHPRequest:myRequestString toPage:@"http://www.mysite.com/mypage.php" delegate:nil]; } -(void) postAsynchronousPHPRequest:(NSString*)request toPage:(NSString*)URL delegate:(id)delegate{ NSData *requestData = [ NSData dataWithBytes: [ request UTF8String ] length: [ request length ] ]; NSMutableURLRequest *URLrequest = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString: URL ] ]; [ URLrequest setHTTPMethod: @"POST" ]; [ URLrequest setHTTPBody: requestData ]; [ NSURLConnection connectionWithRequest:URLrequest delegate:delegate]; [URLrequest release]; } The PHP: $word = $_POST['word']; file_put_contents('log_file_name', "log: ".$word, FILE_APPEND); What am I doing wrong in the Objective-C that would cause the $_POST variable to be empty on the server?

    Read the article

  • returning autorelease NSString still causes memory leaks

    - by hookjd
    I have a simple function that returns an NSString after decoding it. I use it a lot throughout my application, and it appears to create a memory leak (according to "leaks" tool) every time I use it. Leaks tells me the problem is on the line where I alloc the NSString that I am going to return, even though I autorelease it. Here is the function: -(NSString *) decodeValue { NSString *newString; newString = [self stringByReplacingOccurrencesOfString:@"#" withString:@"$"]; NSData *stateData = [NSData dataWithBase64EncodedString:newString]; NSString *convertState = [[[NSString alloc] initWithData:stateData encoding:NSUTF8StringEncoding] autorelease]; return convertState; } My understanding of [autorelease] is that it should be used in exactly this way... where I want to hold onto the object just long enough to return it in my function and then let the object be autoreleased later. So I believe I can use this function through code like this without manually releasing anything: NSString *myDecodedString = [myString decodeValue]; But this process is reporting leaks and I don't understand how to change it to avoid the leaks. What am I doing wrong?

    Read the article

  • iPhone AVAudioPlayer failed to find codec

    - by Anthony
    Hello, I am writing an app that downloads a wav file from a server and needs to play that file. The files use the mulaw codec with 2:1 compression. These wav files are dynamically created by a seperate process so there is no way for me to preconvert the files to a different format or codec, I need to be able to play them as is. I am using an AVAudioPlayer instance initialized as follows: NSURL *audioURL = [[NSURL alloc] initWithString:@"http://xxx.../file.wav"]; NSData *audioData = [[NSData alloc] initWithContentsOfURL:audioURL]; AVAudioPlayer *audio = [[AVAudioPlayer alloc] initWithData:audioData error:nil]; [audio play]; However, when the play method executes, I get the following Console Output when executing on the Simulator: AudioQueue codec policy 1: failed to find a codec of the requested type I also tried saving the downloaded data to a local file and using a file URL, however that yeilds the same results. The downloaded file does play fine on both Mac and Windows based desktop media players. The SDK docs state that the mulaw codec is supported on the iPhone, so I am unsure why it is failing to find it. Any assistance would be greatly appreciated. Thanks.

    Read the article

  • http-post request for a long String in iOS

    - by onkar
    I am looking to send a very long String, which is an image that is encoded into a String. I need to send that information using POST method. I have implemented the same in Android using key-value pair, I need to implement the same in iOS using key-value pair. Please help me with useful resources/approach. EDIT 1 What have I tried [dictionnary setObject:@"admin" forKey:@"username"]; [dictionnary setObject:@"123123" forKey:@"password"]; NSError *error = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary options:kNilOptions error:&error]; NSString *urlString = @"MY CALL URL"; NSURL *url = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:jsonData]; NSURLResponse *response = NULL; NSError *requestError = NULL; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError]; NSLog(@"response is obtained"); NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ; NSLog(@"%@", responseString); EDIT 2 Error I am getting Request Error Error Domain=kCFErrorDomainCFNetwork Code=303 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 303.)" UserInfo=0x7ba0120 {NSErrorFailingURLKey=http://yahoo.com/, NSErrorFailingURLStringKey=http://yahoo.com/}

    Read the article

  • NSURLConnection receives data even if no data was thrown back

    - by Anna Fortuna
    Let me explain my situation. Currently, I am experimenting long-polling using NSURLConnection. I found this and I decided to try it. What I do is send a request to the server with a timeout interval of 300 secs. (or 5 mins.) Here is a code snippet: NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageAllowedInMemoryOnly timeoutInterval:300]; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err]; Now I want to test if the connection will "hold" the request if no data was thrown back from the server, so what I did was this: if (data != nil) [self performSelectorOnMainThread:@selector(dataReceived:) withObject:data waitUntilDone:YES]; And the function dataReceived: looks like this: - (void)dataReceived:(NSData *)data { NSLog(@"DATA RECEIVED!"); NSString *string = [NSString stringWithUTF8String:[data bytes]]; NSLog(@"THE DATA: %@", string); } Server-side, I created a function that will return a data once it fits the arguments and returns none if nothing fits. Here is a snippet of the PHP function: function retrieveMessages($vardata) { if (!empty($vardata)) { $result = check_data($vardata) //check_data is the function which returns 1 if $vardata //fits the arguments, and 0 if it fails to fit if ($result == 1) { $jsonArray = array('Data' => $vardata); echo json_encode($jsonArray); } } } As you can see, the function will only return data if the $result is equal to 1. However, even if the function returns nothing, NSURLConnection will still perform the function dataReceived: meaning the NSURLConnection still receives data, albeit an empty one. So can anyone help me here? How will I perform long-polling using NSURLConnection? Basically, I want to maintain the connection as long as no data is returned. So how will I do it? NOTE: I am new to PHP, so if my code is wrong, please point it out so I can correct it.

    Read the article

  • PHP's openssl_sign generates different signature than SSCrypto's sign

    - by pascalj
    I'm writing an OS X client for a software that is written in PHP. This software uses a simple RPC interface to receive and execute commands. The RPC client has to sign the commands he sends to ensure that no MITM can modify any of them. However, as the server was not accepting the signatures I sent from my OS X client, I started investigating and found out that PHP's openssl_sign function generates a different signature for a given private key/data combination than the Objective-C SSCrypto framework (which is only a wrapper for the openssl lib): SSCrypto *crypto = [[SSCrypto alloc] initWithPrivateKey:self.localPrivKey]; NSData *shaed = [self sha1:@"hello"]; [crypto setClearTextWithData:shaed]; NSData *data = [crypto sign]; generates a signature like CtbkSxvqNZ+mAN... The PHP code openssl_sign("hello", $signature, $privateKey); generates a signature like 6u0d2qjFiMbZ+... (For my certain key, of course. base64 encoded) I'm not quite shure why this is happening and I unsuccessfully experimented with different hash-algorithms. As the PHP documentation states SHA1 is used by default. So why do these two functions generate different signatures and how can I get my Objective-C part to generate a signature that PHPs openssl_verify will accept? Note: I double checked that the keys and the data is correct!

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >