Search Results

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

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

  • Gradual memory leak in loop over contents of QTMovie

    - by Benji XVI
    I have a simple foundation tool that exports every frame of a movie as a .tiff file. Here is the relevant code: NSString* movieLoc = [NSString stringWithCString:argv[1]]; QTMovie *sourceMovie = [QTMovie movieWithFile:movieLoc error:nil]; int i=0; while (QTTimeCompare([sourceMovie currentTime], [sourceMovie duration]) != NSOrderedSame) { // save image of movie to disk NSAutoreleasePool *arp = [[NSAutoreleasePool alloc] init]; NSString *filePath = [NSString stringWithFormat:@"/somelocation_%d.tiff", i++]; NSData *currentImageData = [[sourceMovie currentFrameImage] TIFFRepresentation]; [currentImageData writeToFile:filePath atomically:NO]; NSLog(@"%@", filePath); [sourceMovie stepForward]; [arp release]; } [pool drain]; return 0; As you can see, in order to prevent very large memory buildups with the various transparently-autoreleased variables in the loop, we create, and flush, an autoreleasepool with every run through the loop. However, over the course of stepping through a movie, the amount of memory used by the program still gradually increases. Instruments is not detecting any memory leaks per se, but the object trace shows certain General Data blocks to be increasing in size. [Edited out reference to slowdown as it doesn't seem to be as much of a problem as I thought.] Edit: let's knock out some parts of the code inside the loop & see what we find out... Test 1 while (banana) { NSAutoreleasePool *arp = [[NSAutoreleasePool alloc] init]; NSString *filePath = [NSString stringWithFormat:@"/somelocation_%d.tiff", i++]; NSLog(@"%@", filePath); [sourceMovie stepForward]; [arp release]; } Here we simply loop over the whole movie, creating the filename and logging it. Memory characteristics: remains at 15MB usage for the duration. Test 2 while (banana) { NSAutoreleasePool *arp = [[NSAutoreleasePool alloc] init]; NSImage *image = [sourceMovie currentFrameImage]; [sourceMovie stepForward]; [arp release]; } Here we add back in the creation of the NSImage from the current frame. Memory characteristics: gradually increasing memory usage. RSIZE is at 60MB by frame 200; 75MB by f300. Test 3 while (banana) { NSAutoreleasePool *arp = [[NSAutoreleasePool alloc] init]; NSImage *image = [sourceMovie currentFrameImage]; NSData *imageData = [image TIFFRepresentation]; [sourceMovie stepForward]; [arp release]; } We've added back in the creation of an NSData object from the NSImage. Memory characteristics: Memory usage is again increasing: 62MB at f200; 75MB at f300. In other words, largely identical. It looks like a memory leak in the underlying system QTMovie uses to do currentFrameImage, to me.

    Read the article

  • Save UIView's representation to file.

    - by fish potato
    What is the easiest way to save UIView's representation to file? My solution is, UIGraphicsBeginImageContext(someView.frame.size); [someView drawRect:someView.frame]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSString* pathToCreate = @"sample.png"; NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)]; [imageData writeToFile:pathToCreate atomically:YES]; but it seems tricky, and I think there must be more efficient way to do this.

    Read the article

  • Loading images to UIScrollview crashes

    - by Icky
    Hello All. I have a Navigationcontroller pushing a UIViewController with a scrollview inside. Within the scrollview I download a certain number of images around 20 (sometimes more) each sized around 150 KB. All these images are added to the scrollview so that their origin is x +imageSize and the following is sorted right to the one before. All in all I think its a lot of data (3-4 MB). On an I pod Touch this sometimes crashes, the IPhone can handle it once, if it has to load the data again (some other images) , it crashes too. I guess its a memory issue but within my code, I download the image, save it to a file on the phone as NSData, read it again from file and add it to a UIImageview which I release. So I have freed the memory I allocated, nevertheless it still crashes. Can anyone help me out? Since Im new to this, I dont know the best way to handle the Images in a scrollview. Besides I create the controller at start from nib, which means I dont have to release it, since I dont use alloc - right? Code: In my rootviewcontroller I do: -(void) showImages { [[self naviController] pushViewController:imagesViewController animated:YES]; [imagesViewController viewWillAppear:YES]; } Then in my Controller handling the scroll View, this is the method to load the images: - (void) loadOldImageData { for (int i = 0; i < 40 ; i++) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"img%d.jpg", i]]; NSData *myImg = [NSData dataWithContentsOfFile:filePath]; UIImage *im = [UIImage imageWithData:myImg]; if([im isKindOfClass:[UIImage class]]) { NSLog(@"IM EXISTS"); UIImageView *imgView = [[UIImageView alloc] initWithImage:im]; CGRect frame = CGRectMake(i*320, 0, 320, 416); imgView.frame = frame; [myScrollView addSubview:imgView]; [imgView release]; //NSLog(@"Adding img %d", i); numberImages = i; NSLog(@"setting numberofimages to %d", numberImages); //NSLog(@"scroll subviews %d", [myScrollView.subviews count]); } } myScrollView.contentSize = CGSizeMake(320 * (numberImages + 1), 416); }

    Read the article

  • Using NSThread to solve waiting for image from URL on the iPhone

    - by james.ingham
    So I have the following code in a method which I want to set a UIImageView image to that of one from an online source: [NSThread detachNewThreadSelector:@selector(loadImage) toTarget:self withObject:nil]; Then in the method called by the thread I have this: - (void) loadImage { NSURL *url = [NSURL URLWithString:logoPath]; // logoPath is an NSString with path details NSData *data = [NSData dataWithContentsOfURL:url]; logoImage.image = [UIImage imageWithData:data]; } This works great however I get many warnings within the Debugger Console along the lines of: 2010-05-10 14:30:14.052 ProjectTitle[2930:633f] * _NSAutoreleaseNoPool(): Object 0x169d30 of class NSHTTPURLResponse autoreleased with no pool in place - just leaking This occurs many times each time I call the new thread and then eventually, under no pattern, after calling a few of these threads I get the classic 'EXC_BAD_ACCESS' run-time error. I understand that this is happening because I'm not retaining the object but how can I solve this with the code in 'loadImage' shown above? Thanks

    Read the article

  • How do I convert a NSString into TIS-620 encoded string

    - by MacPC
    In the apple document, I can see that there's a way to convert from UTF8 string to ASCII string like this NSData *asciiData = [theString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *asciiString = [[NSString alloc] initWithData:asciiData encoding:NSASCIIStringEncoding]; But my app requires a TIS-620 string to post to a site so I try to do the same thing NSData *asciiData = [newPost.header dataUsingEncoding:kCFStringEncodingMacThai allowLossyConversion:YES]; NSString *asciiString = [[NSString alloc] initWithData:asciiData encoding:kCFStringEncodingMacThai]; NSLog(@"%@", asciiString); The output I got is like this ???????????. Does anyone know how to convert the NSString to TIS-620 properly? Thanks so much.

    Read the article

  • How to load image form NSMutableArray

    - by pbcoder
    I want to load the image URL from my NSMutableArray. Here is my Code: id path = (NSString *)[[stories objectAtIndex: storyIndex] objectForKey: @"icon"]; NSURL *url = [NSURL URLWithString:path]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *img = [[UIImage alloc] initWithData:data cache:NO]; If I use: id path = @"http://www.xzy.de/icon.png"; it´s all right, but not if I want to extract the imageURL from my Array Anyone who can help me? Thanks!

    Read the article

  • How do you create a writable copy of a sqlite database that is included in your iPhone Xcode project

    - by Iggy
    copy it over to your documents directory when the app starts. Assuming that your sqlite db is in your project, you can use the below code to copy your database to your documents directory. We are also assuming that your database is called mydb.sqlite. //copy the database to documents NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"mydb.sqlite"]; if(![fileManager fileExistsAtPath:path]) { NSData *data = [NSData dataWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/mydb.sqlite"]]; [data writeToFile:path atomically:YES]; } Anyone know of a better way to do this. This seems to work ...

    Read the article

  • Load image from server on a UIImageView in phone

    - by Pedro Narvaez
    Hi.. I'm having a problem loading a remote image into a UIImageVIew... It just doesn't show the image, may be i'm missing something... I also use the described here but with the same results How to load image from remote server on the UIImageView in iphone? Can someone help me? This is the code i'm using Im getting the data from a xml and on the image element I have the full path [[detailViewController detailImage] setImage:[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: [NSString stringWithFormat:@"%@", [[promoList objectAtIndex: promoIndex] objectForKey: @"image"]] ]]] ]; With this code the image are displayed correctly [[detailViewController detailImage] setImage:[UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: @"http://localhost/promos/preview/1.jpeg"]] ]];

    Read the article

  • GET request, iOS

    - by phnmnn
    I need to do this GET request: http://api.testmy.co.il/api/sync?BID=1049&ClientCode=3847&Discount=2.34&Service=0&Items=[{"Name":"Tax","Price":"2.11","Quantity":"1","SerialID":"1","Remarks":"","Toppings":""}]&Payments=[] In browser I get response: { "Success":true, "Atava":[], "Pending":[], "CallWaiter":false } But in iOS it not work. i try: NSString *requestedURL=[NSString stringWithFormat:@"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{\"Name\":\"Tax\",\"Price\":\"2.11\",\"Quantity\":\"1\",\"SerialID\":\"1\",\"Remarks\":\"\",\"Toppings\":\"\"}]&Payments=[]",BID,num]; NSURL *url = [NSURL URLWithString:requestedURL]; NSURLResponse *response; NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; NSString *theReply = [[NSString alloc] initWithBytes:[GETReply bytes] length:[GETReply length] encoding: NSASCIIStringEncoding]; NSLog(@"Reply: %@", theReply); OR NSString *requestedURL=[NSString stringWithFormat:@"http://api.testmy.co.il/api/sync?BID=%i&ClientCode=%i&Discount=2.34&Service=0&Items=[{'Name':'Tax','Price':'2.11','Quantity':'1','SerialID':'1','Remarks':'','Toppings':''}]&Payments=[]",BID,num]; OR NSMutableDictionary *params = [[NSMutableDictionary alloc] init]; [params setObject:@"Tax" forKey:@"Name"]; [params setObject:@"2.11" forKey:@"Price"]; [params setObject:@"1" forKey:@"Quantity"]; [params setObject:@"1" forKey:@"SerialID"]; [params setObject:@"" forKey:@"Remarks"]; [params setObject:@"" forKey:@"Toppings"]; NSData *jsonData = nil; NSString *jsonString = nil; if([NSJSONSerialization isValidJSONObject:params]) { jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil]; jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"%@",jsonString); } NSString *get=[NSString stringWithFormat: @"&Items=%@", jsonString]; NSData *getData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; [request setHTTPMethod:@"GET"]; [request setTimeoutInterval:8]; [request setHTTPBody:getData]; [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; nothing doesn't work. How to fix it? Sorry for bad english.

    Read the article

  • Weird IF THAN not working with Requested data from URL text problem

    - by StealthRT
    Hey all, i am checking for an internet connection by checking for a file on my server. The file only has the word LIVE displayed on the page. No HTML or anything else is there, just the word LIVE. When i run this code, i do get the NSLog as saying "LIVE" but once i go to check it with the IF statement, it fails and i just do not know why??? NSString* myFile = [NSString stringWithFormat:@"http://www.xxx.com/iPodTouchPing.html"]; NSString* myFileURLString = [myFile stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; NSData *myFileData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myFileURLString]]; NSString *returnedMyFileContents=[[[NSString alloc] initWithData:myFileData encoding:NSASCIIStringEncoding] autorelease]; NSLog(@"%@", connected); if (connected == @"LIVE") { ... What am i doing wrong? I can not seem to find the reason?? David

    Read the article

  • Get image from website url iphone faster

    - by dragon
    Hi i want to get image faster from website in iphone.. Now i get image from website url using this function NSData *data; UIImage *Favimage; data = [NSData dataWithContentsOfURL:[NSURL URLWithString:WebsiteUrl]]; Favimage = [[UIImage alloc]initWithData:data]; But it takes some time to get image from website url. Now i want get faster image means ? What can i do ? Is there any api in apple iphone sdk? Can any one help me ? Thanks in advance.....

    Read the article

  • Why would I want to have a non-standard attribute?

    - by dontWatchMyProfile
    The documentation on Core Data entities says: You might implement a custom class, for example, to provide custom accessor or validation methods, to use non-standard attributes, to specify dependent keys, to calculate derived values, or to implement any other custom logic. I stumbled over the non-standard attributes claim. It's just a guess: If my attribute is anything other than NSString, NSNumber or NSDate I will want to have a non-standard Attribute with special setter and getter methods? So, for example, if I wanted to store an image, this would be a non-standard Attribute with type NSData and a special method, say -(void)setImageWithFileURL:(NSURL*)url which then pulls the image data from the file, puts in in an NSData and assigns it to core data? Or did I get that wrong?

    Read the article

  • How to load image from NSMutableArray

    - by pbcoder
    I want to load the image URL from my NSMutableArray. Here is my Code: id path = (NSString *)[[stories objectAtIndex: storyIndex] objectForKey: @"icon"]; NSURL *url = [NSURL URLWithString:path]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *img = [[UIImage alloc] initWithData:data cache:NO]; If I use: id path = @"http://www.xzy.de/icon.png"; it´s all right, but not if I want to extract the imageURL from my Array Anyone who can help me? Thanks!

    Read the article

  • Is there an autorelease pool in class methods?

    - by mystify
    I have an class method which generates an UIView, like this: + (UIImage*)imageWithFileName:(NSString*)imgFile { UIImage *img = nil; NSBundle *appBundle = [NSBundle mainBundle]; NSString *resourcePath = [appBundle pathForResource:imgFile ofType:nil]; if (resourcePath != nil) { NSURL *imageURL = [NSURL fileURLWithPath:resourcePath]; NSData *data = [[NSData alloc] initWithContentsOfURL:imageURL]; img = [UIImage imageWithData:data]; // should be autoreleased!! [data release]; } return img; } However, when I use this, the image data is NEVER freed. There is definitely a memory bug with this, although I didn't break any memory management rule I am aware of. My guess is that because this is a class method which gets called from instance methods, There is no active autorelease pool in place or it's one that only gets drained when I quit the app. Could that be right?

    Read the article

  • how to load local html file into uiwebview iphone

    - by madcoderz
    I'm trying to load a html file into my UIWebView but it won't work. Here's the stage: I have a folder called html_files in my project. Then I created a webView in interface builder and assigned an outlet to it in the viewController. This is the code I'm using to append the html file: -(void)viewDidLoad { NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html" inDirectory:@"html_files"]; NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile]; [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]]; [super viewDidLoad]; } That won't work and the UIWebView is blank. I'd appreciate some help.

    Read the article

  • Uploading video file to server from iPhone

    - by SshUser
    I know how to upload images to a server running PHP, but I am stuck on uploading video. I have used this advice to upload my video file. Posting method is all ok. What I get on the server is a file of 0 bytes. My code is below: - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL]; NSData *videoData = [NSData dataWithContentsOfFile:[videoURL path]]; } This videoData is passed in my POST method. What should I do instead?

    Read the article

  • How To show document directory save image in thumbnail in cocos2d class

    - by Anil gupta
    I have just implemented multiple photo selection from iphone photo library and i am saving all selected photo in document directory every time as a array, now i want to show all saved images in my class from document directory as a thumbnail, i have tried some logic but my game getting crashing, My code is below. Any help will be appreciate. Thanks in advance. -(id) init { // always call "super" init // Apple recommends to re-assign "self" with the "super" return value if( (self=[super init])) { CCSprite *photoalbumbg = [CCSprite spriteWithFile:@"photoalbumbg.png"]; photoalbumbg.anchorPoint = ccp(0,0); [self addChild:photoalbumbg z:0]; //Background Sound // [[SimpleAudioEngine sharedEngine]playBackgroundMusic:@"Background Music.wav" loop:YES]; CCSprite *photoalbumframe = [CCSprite spriteWithFile:@"photoalbumframe.png"]; photoalbumframe.position = ccp(160,240); [self addChild:photoalbumframe z:2]; CCSprite *frame = [CCSprite spriteWithFile:@"Photo-Frames.png"]; frame.position = ccp(160,270); [self addChild:frame z:1]; /*_____________________________________________________________________________________*/ CCMenuItemImage * upgradebtn = [CCMenuItemImage itemFromNormalImage:@"AlbumUpgrade.png" selectedImage:@"AlbumUpgrade.png" target:self selector:@selector(Upgrade:)]; CCMenu * fMenu = [CCMenu menuWithItems:upgradebtn,nil]; fMenu.position = ccp(200,110); [self addChild:fMenu z:3]; NSError *error; NSFileManager *fM = [NSFileManager defaultManager]; NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; NSLog(@"Documents directory: %@", [fM contentsOfDirectoryAtPath:documentsDirectory error:&error]); NSArray *allfiles = [fM contentsOfDirectoryAtPath :documentsDirectory error:&error]; directoryList = [[NSMutableArray alloc] init]; for(NSString *file in allfiles) { NSString *path = [documentsDirectory stringByAppendingPathComponent:file]; [directoryList addObject:file]; } NSLog(@"array file name value ==== %@", directoryList); CCSprite *temp = [CCSprite spriteWithFile:[directoryList objectAtIndex:0]]; [temp setTextureRect:CGRectMake(160.0f, 240.0f, 50,50)]; // temp.anchorPoint = ccp(0,0); [self addChild:temp z:10]; for(UIImage *file in directoryList) { // NSData *pngData = [NSData dataWithContentsOfFile:file]; // image = [UIImage imageWithData:pngData]; NSLog(@"uiimage = %@",image); // UIImage *image = [UIImage imageWithContentsOfFile:file]; for (int i=1; i<=3; i++) { for (int j=1;j<=3; j++) { CCTexture2D *tex = [[[CCTexture2D alloc] initWithImage:file] autorelease]; CCSprite *selectedimage = [CCSprite spriteWithTexture:tex rect:CGRectMake(0, 0, 67, 66)]; selectedimage.position = ccp(100*i,350*j); [self addChild:selectedimage]; } } } } return self; }

    Read the article

  • UIImagePickerController, UIImage, Memory and More!

    - by Itay
    I've noticed that there are many questions about how to handle UIImage objects, especially in conjunction with UIImagePickerController and then displaying it in a view (usually a UIImageView). Here is a collection of common questions and their answers. Feel free to edit and add your own. I obviously learnt all this information from somewhere too. Various forum posts, StackOverflow answers and my own experimenting brought me to all these solutions. Credit goes to those who posted some sample code that I've since used and modified. I don't remember who you all are - but hats off to you! How Do I Select An Image From the User's Images or From the Camera? You use UIImagePickerController. The documentation for the class gives a decent overview of how one would use it, and can be found here. Basically, you create an instance of the class, which is a modal view controller, display it, and set yourself (or some class) to be the delegate. Then you'll get notified when a user selects some form of media (movie or image in 3.0 on the 3GS), and you can do whatever you want. My Delegate Was Called - How Do I Get The Media? The delegate method signature is the following: - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info; You should put a breakpoint in the debugger to see what's in the dictionary, but you use that to extract the media. For example: UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage]; There are other keys that work as well, all in the documentation. OK, I Got The Image, But It Doesn't Have Any Geolocation Data. What gives? Unfortunately, Apple decided that we're not worthy of this information. When they load the data into the UIImage, they strip it of all the EXIF/Geolocation data. Can I Get To The Original File Representing This Image on the Disk? Nope. For security purposes, you only get the UIImage. How Can I Look At The Underlying Pixels of the UIImage? Since the UIImage is immutable, you can't look at the direct pixels. However, you can make a copy. The code to this looks something like this: UIImage* image = ...; // An image NSData* pixelData = (NSData*) CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage)); unsigned char* pixelBytes = (unsigned char *)[pixelData bytes]; // Take away the red pixel, assuming 32-bit RGBA for(int i = 0; i < [pixelData length]; i += 4) { pixelBytes[i] = 0; // red pixelBytes[i+1] = pixelBytes[i+1]; // green pixelBytes[i+2] = pixelBytes[i+2]; // blue pixelBytes[i+3] = pixelBytes[i+3]; // alpha } However, note that CGDataProviderCopyData provides you with an "immutable" reference to the data - meaning you can't change it (and you may get a BAD_ACCESS error if you do). Look at the next question if you want to see how you can modify the pixels. How Do I Modify The Pixels of the UIImage? The UIImage is immutable, meaning you can't change it. Apple posted a great article on how to get a copy of the pixels and modify them, and rather than copy and paste it here, you should just go read the article. Once you have the bitmap context as they mention in the article, you can do something similar to this to get a new UIImage with the modified pixels: CGImageRef ref = CGBitmapContextCreateImage(bitmap); UIImage* newImage = [UIImage imageWithCGImage:ref]; Do remember to release your references though, otherwise you're going to be leaking quite a bit of memory. After I Select 3 Images From The Camera, I Run Out Of Memory. Help! You have to remember that even though on disk these images take up only a few hundred kilobytes at most, that's because they're compressed as a PNG or JPG. When they are loaded into the UIImage, they become uncompressed. A quick over-the-envelope calculation would be: width x height x 4 = bytes in memory That's assuming 32-bit pixels. If you have 16-bit pixels (some JPGs are stored as RGBA-5551), then you'd replace the 4 with a 2. Now, images taken with the camera are 1600 x 1200 pixels, so let's do the math: 1600 x 1200 x 4 = 7,680,000 bytes = ~8 MB 8 MB is a lot, especially when you have a limit of around 24 MB for your application. That's why you run out of memory. OK, I Understand Why I Have No Memory. What Do I Do? There is never any reason to display images at their full resolution. The iPhone has a screen of 480 x 320 pixels, so you're just wasting space. If you find yourself in this situation, ask yourself the following question: Do I need the full resolution image? If the answer is yes, then you should save it to disk for later use. If the answer is no, then read the next part. Once you've decided what to do with the full-resolution image, then you need to create a smaller image to use for displaying. Many times you might even want several sizes for your image: a thumbnail, a full-size one for displaying, and the original full-resolution image. OK, I'm Hooked. How Do I Resize the Image? Unfortunately, there is no defined way how to resize an image. Also, it's important to note that when you resize it, you'll get a new image - you're not modifying the old one. There are a couple of methods to do the resizing. I'll present them both here, and explain the pros and cons of each. Method 1: Using UIKit + (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize; { // Create a graphics image context UIGraphicsBeginImageContext(newSize); // Tell the old image to draw in this new context, with the desired // new size [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; // Get the new image from the context UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); // End the context UIGraphicsEndImageContext(); // Return the new image. return newImage; } This method is very simple, and works great. It will also deal with the UIImageOrientation for you, meaning that you don't have to care whether the camera was sideways when the picture was taken. However, this method is not thread safe, and since thumbnailing is a relatively expensive operation (approximately ~2.5s on a 3G for a 1600 x 1200 pixel image), this is very much an operation you may want to do in the background, on a separate thread. Method 2: Using CoreGraphics + (UIImage*)imageWithImage:(UIImage*)sourceImage scaledToSize:(CGSize)newSize; { CGFloat targetWidth = targetSize.width; CGFloat targetHeight = targetSize.height; CGImageRef imageRef = [sourceImage CGImage]; CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef); if (bitmapInfo == kCGImageAlphaNone) { bitmapInfo = kCGImageAlphaNoneSkipLast; } CGContextRef bitmap; if (sourceImage.imageOrientation == UIImageOrientationUp || sourceImage.imageOrientation == UIImageOrientationDown) { bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo); } else { bitmap = CGBitmapContextCreate(NULL, targetHeight, targetWidth, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo); } if (sourceImage.imageOrientation == UIImageOrientationLeft) { CGContextRotateCTM (bitmap, radians(90)); CGContextTranslateCTM (bitmap, 0, -targetHeight); } else if (sourceImage.imageOrientation == UIImageOrientationRight) { CGContextRotateCTM (bitmap, radians(-90)); CGContextTranslateCTM (bitmap, -targetWidth, 0); } else if (sourceImage.imageOrientation == UIImageOrientationUp) { // NOTHING } else if (sourceImage.imageOrientation == UIImageOrientationDown) { CGContextTranslateCTM (bitmap, targetWidth, targetHeight); CGContextRotateCTM (bitmap, radians(-180.)); } CGContextDrawImage(bitmap, CGRectMake(0, 0, targetWidth, targetHeight), imageRef); CGImageRef ref = CGBitmapContextCreateImage(bitmap); UIImage* newImage = [UIImage imageWithCGImage:ref]; CGContextRelease(bitmap); CGImageRelease(ref); return newImage; } The benefit of this method is that it is thread-safe, plus it takes care of all the small things (using correct color space and bitmap info, dealing with image orientation) that the UIKit version does. How Do I Resize and Maintain Aspect Ratio (like the AspectFill option)? It is very similar to the method above, and it looks like this: + (UIImage*)imageWithImage:(UIImage*)sourceImage scaledToSizeWithSameAspectRatio:(CGSize)targetSize; { CGSize imageSize = sourceImage.size; CGFloat width = imageSize.width; CGFloat height = imageSize.height; CGFloat targetWidth = targetSize.width; CGFloat targetHeight = targetSize.height; CGFloat scaleFactor = 0.0; CGFloat scaledWidth = targetWidth; CGFloat scaledHeight = targetHeight; CGPoint thumbnailPoint = CGPointMake(0.0,0.0); if (CGSizeEqualToSize(imageSize, targetSize) == NO) { CGFloat widthFactor = targetWidth / width; CGFloat heightFactor = targetHeight / height; if (widthFactor > heightFactor) { scaleFactor = widthFactor; // scale to fit height } else { scaleFactor = heightFactor; // scale to fit width } scaledWidth = width * scaleFactor; scaledHeight = height * scaleFactor; // center the image if (widthFactor > heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else if (widthFactor < heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; } } CGImageRef imageRef = [sourceImage CGImage]; CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef); if (bitmapInfo == kCGImageAlphaNone) { bitmapInfo = kCGImageAlphaNoneSkipLast; } CGContextRef bitmap; if (sourceImage.imageOrientation == UIImageOrientationUp || sourceImage.imageOrientation == UIImageOrientationDown) { bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo); } else { bitmap = CGBitmapContextCreate(NULL, targetHeight, targetWidth, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo); } // In the right or left cases, we need to switch scaledWidth and scaledHeight, // and also the thumbnail point if (sourceImage.imageOrientation == UIImageOrientationLeft) { thumbnailPoint = CGPointMake(thumbnailPoint.y, thumbnailPoint.x); CGFloat oldScaledWidth = scaledWidth; scaledWidth = scaledHeight; scaledHeight = oldScaledWidth; CGContextRotateCTM (bitmap, radians(90)); CGContextTranslateCTM (bitmap, 0, -targetHeight); } else if (sourceImage.imageOrientation == UIImageOrientationRight) { thumbnailPoint = CGPointMake(thumbnailPoint.y, thumbnailPoint.x); CGFloat oldScaledWidth = scaledWidth; scaledWidth = scaledHeight; scaledHeight = oldScaledWidth; CGContextRotateCTM (bitmap, radians(-90)); CGContextTranslateCTM (bitmap, -targetWidth, 0); } else if (sourceImage.imageOrientation == UIImageOrientationUp) { // NOTHING } else if (sourceImage.imageOrientation == UIImageOrientationDown) { CGContextTranslateCTM (bitmap, targetWidth, targetHeight); CGContextRotateCTM (bitmap, radians(-180.)); } CGContextDrawImage(bitmap, CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledWidth, scaledHeight), imageRef); CGImageRef ref = CGBitmapContextCreateImage(bitmap); UIImage* newImage = [UIImage imageWithCGImage:ref]; CGContextRelease(bitmap); CGImageRelease(ref); return newImage; } The method we employ here is to create a bitmap with the desired size, but draw an image that is actually larger, thus maintaining the aspect ratio. So We've Got Our Scaled Images - How Do I Save Them To Disk? This is pretty simple. Remember that we want to save a compressed version to disk, and not the uncompressed pixels. Apple provides two functions that help us with this (documentation is here): NSData* UIImagePNGRepresentation(UIImage *image); NSData* UIImageJPEGRepresentation (UIImage *image, CGFloat compressionQuality); And if you want to use them, you'd do something like: UIImage* myThumbnail = ...; // Get some image NSData* imageData = UIImagePNGRepresentation(myThumbnail); Now we're ready to save it to disk, which is the final step (say into the documents directory): // Give a name to the file NSString* imageName = @"MyImage.png"; // Now, we have to find the documents directory so we can save it // Note that you might want to save it elsewhere, like the cache directory, // or something similar. NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString* documentsDirectory = [paths objectAtIndex:0]; // Now we get the full path to the file NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName]; // and then we write it out [imageData writeToFile:fullPathToFile atomically:NO]; You would repeat this for every version of the image you have. How Do I Load These Images Back Into Memory? Just look at the various UIImage initialization methods, such as +imageWithContentsOfFile: in the Apple documentation.

    Read the article

  • Post data to aspx page from iphone application

    - by Dipen
    Hi, I am developing a application. In which i am posting a image to .aspx page.The HTML for the page is as below. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>"> <html xmlns="http://www.w3.org/1999/xhtml>"> <head><title> Untitled Page </title><link href="App_Themes/XXX/XXX.css" type="text/css" rel="stylesheet" /></head> <body> <form name="form1" method="post" action="Default16.aspx" id="form1" enctype="multipart/form-data"> <div> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTQwMjY2MDA0Mw9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRktr+hG1VVXZsO01PCyj61d6Ulqy8=" /> </div> <div> <div style="float:left;margin:10px"> <input type="file" name="fuImage" id="fuImage" /> </div> <div style="float:right"> <input type="submit" name="btnPost" value="Post Image" id="btnPost" /> </div> </div> </form> </body> </html> Now i am sending a request from my application then i am getting " Error Domain=kCFErrorDomainCFNetwork Code=303 UserInfo=0xf541c0 "Operation could not be completed. (kCFErrorDomainCFNetwork error 303.)"" I have tried using SynchronousRequest and aSynchronousRequest but both are not working. I have also used apple sample code. Here is the code for iPhone app UIImage *image=[UIImage imageNamed:@"photo2.jpg"]; NSData *imageData = UIImageJPEGRepresentation(image, 90); NSString *urlString = @"http://XXXXXXXX.com/Post.aspx"; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSString *boundary = [NSString stringWithString:@"----WebKitFormBoundarylU9pAl5wPrF+Tk52"]; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [request addValue:contentType forHTTPHeaderField:@"Content-Type"]; NSMutableData *body = [NSMutableData data]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"fuimage\"; filename=\"asd.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[NSData dataWithData:imageData]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; // NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; // NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; // NSLog(returnString); NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if( theConnection ) { webData = [[NSMutableData data] retain]; } else { NSLog(@"theConnection is NULL"); } Thanks in Advance.

    Read the article

  • zLib on iPhone, stop at first BLOCK

    - by cedric
    I am trying to call iPhone zLib to decompress the zlib stream from our HTTP based server, but the code always stop after finishing the first zlib block. Obviously, iPhone SDK is using the standard open Zlib. My doubt is that the parameter for inflateInit2 is not appropriate here. I spent lots of time reading the zlib manual, but it isn't that helpful. Here is the details, your help is appreciated. (1) the HTTP request: NSURL *url = [NSURL URLWithString:@"http://192.168.0.98:82/WIC?query=getcontacts&PIN=12345678&compression=Y"]; (2) The data I get from server is something like this (if decompressed). The stream was compressed by C# zlib class DeflateStream: $REC_TYPE=SYS Status=OK Message=OK SetID= IsLast=Y StartIndex=0 LastIndex=6 EOR ...... $REC_TYPE=CONTACTSDISTLIST ID=2 Name=CTU+L%2EA%2E OnCallEnabled=Y OnCallMinUsers=1 OnCallEditRight= OnCallEditDLRight=D Fields= CL= OnCallStatus= EOR (3) However, I will only get the first Block. The code for decompression on iPhone (copied from a code piece from somewhere here) is as follow. The loop between Line 23~38 always break the second time execution. + (NSData *) uncompress: (NSData*) data { 1 if ([data length] == 0) return nil; 2 NSInteger length = [data length]; 3 unsigned full_length = length; 4 unsigned half_length =length/ 2; 5 NSMutableData *decompressed = [NSMutableData dataWithLength: 5*full_length + half_length]; 6 BOOL done = NO; 7 int status; 8 z_stream strm; 9 length=length-4; 10 void* bytes= malloc(length); 11 NSRange range; 12 range.location=4; 13 range.length=length; 14 [data getBytes: bytes range: range]; 15 strm.next_in = bytes; 16 strm.avail_in = length; 17 strm.total_out = 0; 18 strm.zalloc = Z_NULL; 19 strm.zfree = Z_NULL; 20 strm.data_type= Z_BINARY; 21 // if (inflateInit(&strm) != Z_OK) return nil; 22 if (inflateInit2(&strm, (-15)) != Z_OK) return nil; //It won't work if change -15 to positive numbers. 23 while (!done) 24 { 25 // Make sure we have enough room and reset the lengths. 26 if (strm.total_out >= [decompressed length]) 27 [decompressed increaseLengthBy: half_length]; 28 strm.next_out = [decompressed mutableBytes] + strm.total_out; 29 strm.avail_out = [decompressed length] - strm.total_out; 30 31 // Inflate another chunk. 32 status = inflate (&strm, Z_SYNC_FLUSH); //Z_SYNC_FLUSH-->Z_BLOCK, won't work either 33 if (status == Z_STREAM_END){ 34 35 done = YES; 36 } 37 else if (status != Z_OK) break; 38 } 39 if (inflateEnd (&strm) != Z_OK) return nil; 40 // Set real length. 41 if (done) 42 { 43 [decompressed setLength: strm.total_out]; 44 return [NSData dataWithData: decompressed]; 45 } 46 else return nil; 47 }

    Read the article

  • Find out when all processes in (void) is done?

    - by Emil
    Hey. I need to know how you can find out when all processes (loaded) from a - (void) are done, if it's possible. Why? I'm loading in data for a UITableView, and I need to know when a Loading... view can be replaced with the UITableView, and when I can start creating the cells. This is my code: - (void) reloadData { NSAutoreleasePool *releasePool = [[NSAutoreleasePool alloc] init]; NSLog(@"Reloading data."); NSURL *urlPosts = [NSURL URLWithString:[NSString stringWithFormat:@"%@", URL]]; NSError *lookupError = nil; NSString *data = [[NSString alloc] initWithContentsOfURL:urlPosts encoding:NSUTF8StringEncoding error:&lookupError]; postsData = [data componentsSeparatedByString:@"~"]; [data release], data = nil; urlPosts = nil; self.numberOfPosts = [[postsData objectAtIndex:0] intValue]; self.postsArrayID = [[postsData objectAtIndex:1] componentsSeparatedByString:@"#"]; self.postsArrayDate = [[postsData objectAtIndex:2] componentsSeparatedByString:@"#"]; self.postsArrayTitle = [[postsData objectAtIndex:3] componentsSeparatedByString:@"#"]; self.postsArrayComments = [[postsData objectAtIndex:4] componentsSeparatedByString:@"#"]; self.postsArrayImgSrc = [[postsData objectAtIndex:5] componentsSeparatedByString:@"#"]; NSMutableArray *writeToPlist = [NSMutableArray array]; NSMutableArray *writeToNoImagePlist = [NSMutableArray array]; NSMutableArray *imagesStored = [NSMutableArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:@"imagesStored.plist"]]; int loop = 0; for (NSString *postID in postsArrayID) { if ([imagesStored containsObject:[NSString stringWithFormat:@"%@.png", postID]]){ NSLog(@"Allready stored, jump to next. ID: %@", postID); continue; } NSLog(@"%@.png", postID); NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[postsArrayImgSrc objectAtIndex:loop]]]; // If image contains anything, set cellImage to image. If image is empty, try one more time or use noImage.png, set in IB if (imageData == nil){ NSLog(@"imageData is empty before trying .jpeg"); // If image == nil, try to replace .jpg with .jpeg, and if that worked, set cellImage to that image. If that is also nil, use noImage.png, set in IB. imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[postsArrayImgSrc objectAtIndex:loop] stringByReplacingOccurrencesOfString:@".jpg" withString:@".jpeg"]]]; } if (imageData != nil){ NSLog(@"imageData is NOT empty when creating file"); [fileManager createFileAtPath:[rootPath stringByAppendingPathComponent:[NSString stringWithFormat:@"images/%@.png", postID]] contents:imageData attributes:nil]; [writeToPlist addObject:[NSString stringWithFormat:@"%@.png", postID]]; } else { [writeToNoImagePlist addObject:[NSString stringWithFormat:@"%@", postID]]; } imageData = nil; loop++; NSLog(@"imagePlist: %@\nnoImagePlist: %@", writeToPlist, writeToNoImagePlist); } NSMutableArray *writeToAllPlist = [NSMutableArray arrayWithArray:writeToPlist]; [writeToPlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:nowPlist]]; [writeToAllPlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:@"imagesStored.plist"]]]; [writeToNoImagePlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:@"noImage.plist"]]]; [writeToPlist writeToFile:nowPlist atomically:YES]; [writeToAllPlist writeToFile:[rootPath stringByAppendingPathComponent:@"imagesStored.plist"] atomically:YES]; [writeToNoImagePlist writeToFile:[rootPath stringByAppendingPathComponent:@"noImage.plist"] atomically:YES]; [releasePool release]; }

    Read the article

  • can't able to integrate base64decode in my class

    - by MaheshBabu
    Hi folks, i am getting the image that is in base64 encoded format. I need to decode it. i am writing the code for decoding is + (NSData *) base64DataFromString: (NSString *)string { unsigned long ixtext, lentext; unsigned char ch, input[4], output[3]; short i, ixinput; Boolean flignore, flendtext = false; const char *temporary; NSMutableData *result; if (!string) return [NSData data]; ixtext = 0; temporary = [string UTF8String]; lentext = [string length]; result = [NSMutableData dataWithCapacity: lentext]; ixinput = 0; while (true) { if (ixtext >= lentext) break; ch = temporary[ixtext++]; flignore = false; if ((ch >= 'A') && (ch <= 'Z')) ch = ch - 'A'; else if ((ch >= 'a') && (ch <= 'z')) ch = ch - 'a' + 26; else if ((ch >= '0') && (ch <= '9')) ch = ch - '0' + 52; else if (ch == '+') ch = 62; else if (ch == '=') flendtext = true; else if (ch == '/') ch = 63; else flignore = true; if (!flignore) { short ctcharsinput = 3; Boolean flbreak = false; if (flendtext) { if (ixinput == 0) break; if ((ixinput == 1) || (ixinput == 2)) { ctcharsinput = 1; else ctcharsinput = 2; ixinput = 3; flbreak = true; } input[ixinput++] = ch; if (ixinput == 4) ixinput = 0; output[0] = (input[0] << 2) | ((input[1] & 0x30) >> 4); output[1] = ((input[1] & 0x0F) << 4) | ((input[2] & 0x3C) >> 2); output[2] = ((input[2] & 0x03) << 6) | (input[3] & 0x3F); for (i = 0; i < ctcharsinput; i++) [result appendBytes: &output[i] length: 1]; } if (flbreak) break; } return result; } i am calling this in my method like this NSData *data = [base64DataFromString:theXML]; theXML is encoded data. but it shows error decodeBase64 undeclared. How can i use this method. can any one pls help me. Thank u in advance.

    Read the article

  • PDF rendering crashes app Core Graphics

    - by Felixyz
    EDIT: The memory leaks turned out to be unrelated to the crashes. Leaks are fixed but crashes remain, still mysterious. My (iPhone) app does lots of PDF loading and rendering, some of it threaded. Sometime, it seems always after I flush a page cash after getting a memory warning, the app crashes with a bad access when trying to draw a pdf page stored in an NSData object. Here is one example trace: #0 0x3016d564 in CGPDFResourcesGetResource () #1 0x3016d58a in CGPDFResourcesGetResource () #2 0x3016d94e in CGPDFResourcesGetExtGState () #3 0x3015fac4 in CGPDFContentStreamGetExtGState () #4 0x301629a8 in op_gs () #5 0x3016df12 in handle_xname () #6 0x3016dd9e in read_objects () #7 0x3016de6c in CGPDFScannerScan () #8 0x30161e34 in CGPDFDrawingContextDraw () #9 0x3016a9dc in CGContextDrawPDFPage () But sometimes I get this instead: Program received signal: “EXC_BAD_ACCESS”. (gdb) bt #0 0x335625fa in objc_msgSend () #1 0x32c04eba in CFDictionaryGetValue () #2 0x3016d500 in get_value () #3 0x3016d5d6 in CGPDFResourcesGetFont () #4 0x3015fbb4 in CGPDFContentStreamGetFont () #5 0x30163480 in op_Tf () #6 0x3016df12 in handle_xname () #7 0x3016dd9e in read_objects () #8 0x3016de6c in CGPDFScannerScan () #9 0x30161e34 in CGPDFDrawingContextDraw () #10 0x3016a9dc in CGContextDrawPDFPage () Is this an indication that I've mistakenly deallocated an object? It's hard for me to decode what's happening here. This is how I create and retain the various objects involved: // Some data was just loaded from the network and is pointed to by "data" self.pdfData = data; _dataProviderRef = CGDataProviderCreateWithData( NULL, [_pdfData bytes], [_pdfData length], NULL ); _documentRef = CGPDFDocumentCreateWithProvider(_dataProviderRef); _pageRef = CGPDFDocumentGetPage(_documentRef, 1); CGPDFPageRetain(_pageRef); _pdfFrame = CGPDFPageGetBoxRect(_pageRef, kCGPDFArtBox); So the NSData object is retained, and I explicitly retain the page reference. The data provider and the document are already retained by the create-functions. And here is my dealloc method: -(void)dealloc { if (_pageRef) CGPDFPageRelease(_pageRef); if (_documentRef) CGPDFDocumentRelease(_documentRef); if (_dataProviderRef) CGDataProviderRelease(_dataProviderRef); self.pdfData = nil; [super dealloc]; } Am I doing anything wrong? Even an assurance that I'm not, with explanation, would be a help.

    Read the article

  • little more help with a CATiledLayer

    - by Brodie4598
    Okay so I am trying to adapt an online tutorial for CATiledLayer to use in my app. The example uses a PDF but I need to display a JPG. I'm getting close, but I just cant figure this out. Should I be using a UIImage or something else? #import <QuartzCore/QuartzCore.h> #import "practiceViewController.h" @implementation practiceViewController - (void)viewDidLoad { [super viewDidLoad]; NSBundle *bundle = [[NSBundle mainBundle]autorelease]; NSString *path = [bundle pathForResource:@"H-5" ofType:@"jpg"]; NSData *data = [NSData dataWithContentsOfFile:path]; image = [UIImage imageWithData:data]; CGRect pageRect = CGRectMake(0, 0, 1600, 2400); CATiledLayer *tiledLayer = [CATiledLayer layer]; tiledLayer.delegate = self; tiledLayer.tileSize = CGSizeMake(1024.0, 1024.0); tiledLayer.levelsOfDetail = 1000; tiledLayer.levelsOfDetailBias = 1000; tiledLayer.frame = pageRect; myContentView = [[UIView alloc] initWithFrame:pageRect]; [myContentView.layer addSublayer:tiledLayer]; CGRect viewFrame = self.view.frame; viewFrame.origin = CGPointZero; UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:viewFrame]; scrollView.delegate = self; scrollView.contentSize = pageRect.size; scrollView.maximumZoomScale = 1000; [scrollView addSubview:myContentView]; [self.view addSubview:scrollView]; } - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return myContentView; } - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx { NEED HE:LP WITH THIS } @end

    Read the article

  • iphone twitter posting

    - by user313100
    I have some twitter code I modified from: http://amanpages.com/sample-iphone-example-project/twitteragent-tutorial-tweet-from-iphone-app-in-one-line-code-with-auto-tinyurl/ His code used view alerts to login and post to twitter but I wanted to change mine to use windows. It is mostly working and I can login and post to Twitter. However, when I try to post a second time, the program crashes with a: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFString text]: unrecognized selector sent to instance 0xc2d560' I'm a bit of a coding newbie so any help would be appreciated. If I need to post more code, ask. #import "TwitterController.h" #import "xmacros.h" #define XAGENTS_TWITTER_CONFIG_FILE DOC_PATH(@"xagents_twitter_conifg_file.plist") static TwitterController* agent; @implementation TwitterController BOOL isLoggedIn; @synthesize parentsv, sharedLink; -(id)init { self = [super init]; maxCharLength = 140; parentsv = nil; isLogged = NO; isLoggedIn = NO; txtMessage = [[UITextView alloc] initWithFrame:CGRectMake(30, 225, 250, 60)]; UIImageView* bg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fb_message_bg.png"]]; bg.frame = txtMessage.frame; lblCharLeft = [[UILabel alloc] initWithFrame:CGRectMake(15, 142, 250, 20)]; lblCharLeft.font = [UIFont systemFontOfSize:10.0f]; lblCharLeft.textAlignment = UITextAlignmentRight; lblCharLeft.textColor = [UIColor whiteColor]; lblCharLeft.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; txtUsername = [[UITextField alloc]initWithFrame:CGRectMake(125, 190, 150, 30)]; txtPassword = [[UITextField alloc]initWithFrame:CGRectMake(125, 225, 150, 30)]; txtPassword.secureTextEntry = YES; lblId = [[UILabel alloc]initWithFrame:CGRectMake(15, 190, 100, 30)]; lblPassword = [[UILabel alloc]initWithFrame:CGRectMake(15, 225, 100, 30)]; lblTitle = [[UILabel alloc]initWithFrame:CGRectMake(80, 170, 190, 30)]; lblId.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; lblPassword.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; lblTitle.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; lblId.textColor = [UIColor whiteColor]; lblPassword.textColor = [UIColor whiteColor]; lblTitle.textColor = [UIColor whiteColor]; txtMessage.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; lblId.text = @"Username:"; lblPassword.text =@"Password:"; lblTitle.text = @"Tweet This Message"; lblId.textAlignment = UITextAlignmentRight; lblPassword.textAlignment = UITextAlignmentRight; lblTitle.textAlignment = UITextAlignmentCenter; txtUsername.borderStyle = UITextBorderStyleRoundedRect; txtPassword.borderStyle = UITextBorderStyleRoundedRect; txtMessage.delegate = self; txtUsername.delegate = self; txtPassword.delegate = self; login = [[UIButton alloc] init]; login = [UIButton buttonWithType:UIButtonTypeRoundedRect]; login.frame = CGRectMake(165, 300, 100, 30); [login setTitle:@"Login" forState:UIControlStateNormal]; [login addTarget:self action:@selector(onLogin) forControlEvents:UIControlEventTouchUpInside]; cancel = [[UIButton alloc] init]; cancel = [UIButton buttonWithType:UIButtonTypeRoundedRect]; cancel.frame = CGRectMake(45, 300, 100, 30); [cancel setTitle:@"Back" forState:UIControlStateNormal]; [cancel addTarget:self action:@selector(onCancel) forControlEvents:UIControlEventTouchUpInside]; post = [[UIButton alloc] init]; post = [UIButton buttonWithType:UIButtonTypeRoundedRect]; post.frame = CGRectMake(165, 300, 100, 30); [post setTitle:@"Post" forState:UIControlStateNormal]; [post addTarget:self action:@selector(onPost) forControlEvents:UIControlEventTouchUpInside]; back = [[UIButton alloc] init]; back = [UIButton buttonWithType:UIButtonTypeRoundedRect]; back.frame = CGRectMake(45, 300, 100, 30); [back setTitle:@"Back" forState:UIControlStateNormal]; [back addTarget:self action:@selector(onCancel) forControlEvents:UIControlEventTouchUpInside]; loading1 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; loading1.frame = CGRectMake(140, 375, 40, 40); loading1.hidesWhenStopped = YES; [loading1 stopAnimating]; loading2 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; loading2.frame = CGRectMake(140, 375, 40, 40); loading2.hidesWhenStopped = YES; [loading2 stopAnimating]; twitterWindow = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [twitterWindow addSubview:txtUsername]; [twitterWindow addSubview:txtPassword]; [twitterWindow addSubview:lblId]; [twitterWindow addSubview:lblPassword]; [twitterWindow addSubview:login]; [twitterWindow addSubview:cancel]; [twitterWindow addSubview:loading1]; UIImageView* logo = [[UIImageView alloc] initWithFrame:CGRectMake(35, 165, 48, 48)]; logo.image = [UIImage imageNamed:@"Twitter_logo.png"]; [twitterWindow addSubview:logo]; [logo release]; twitterWindow2 = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [twitterWindow2 addSubview:lblTitle]; [twitterWindow2 addSubview:lblCharLeft]; [twitterWindow2 addSubview:bg]; [twitterWindow2 addSubview:txtMessage]; [twitterWindow2 addSubview:lblURL]; [twitterWindow2 addSubview:post]; [twitterWindow2 addSubview:back]; [twitterWindow2 addSubview:loading2]; [twitterWindow2 bringSubviewToFront:txtMessage]; UIImageView* logo1 = [[UIImageView alloc] initWithFrame:CGRectMake(35, 155, 42, 42)]; logo1.image = [UIImage imageNamed:@"twitter-logo-twit.png"]; [twitterWindow2 addSubview:logo1]; [logo1 release]; twitterWindow.hidden = YES; twitterWindow2.hidden = YES; return self; } -(void) onStart { [[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationPortrait]; twitterWindow.hidden = NO; [twitterWindow makeKeyWindow]; [self refresh]; if(isLogged) { twitterWindow.hidden = YES; twitterWindow2.hidden = NO; [twitterWindow2 makeKeyWindow]; } } - (void)textFieldDidBeginEditing:(UITextField *)textField { [textField becomeFirstResponder]; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return NO; } - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ const char* str = [text UTF8String]; int s = str[0]; if(s!=0) if((range.location + range.length) > maxCharLength){ return NO; }else{ int left = 139 - ([sharedLink length] + [textView.text length]); lblCharLeft.text= [NSString stringWithFormat:@"%d",left]; // this fix was done by Jackie //http://amanpages.com/sample-iphone-example-project/twitteragent-tutorial-tweet-from-iphone-app-in-one-line-code-with-auto-tinyurl/#comment-38026299 if([text isEqualToString:@"\n"]){ [textView resignFirstResponder]; return FALSE; }else{ return YES; } } int left = 139 - ([sharedLink length] + [textView.text length]); lblCharLeft.text= [NSString stringWithFormat:@"%d",left]; return YES; } -(void) onLogin { [loading1 startAnimating]; NSString *postURL = @"http://twitter.com/statuses/update.xml"; NSString *myRequestString = [NSString stringWithFormat:@""]; NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ]; NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:postURL ] ]; [ request setHTTPMethod: @"POST" ]; [ request setHTTPBody: myRequestData ]; NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; if (!theConnection) { UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Failed to Connect to twitter" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; } [request release]; } -(void) onCancel { [[NSUserDefaults standardUserDefaults] setValue:@"NotActive" forKey:@"Twitter"]; twitterWindow.hidden = YES; [[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationLandscapeRight]; } -(void) onPost { [loading2 startAnimating]; NSString *postURL = @"http://twitter.com/statuses/update.xml"; NSString *myRequestString; if(sharedLink){ myRequestString = [NSString stringWithFormat:@"&status=%@",[NSString stringWithFormat:@"%@\n%@",txtMessage.text,sharedLink]]; }else{ myRequestString = [NSString stringWithFormat:@"&status=%@",[NSString stringWithFormat:@"%@",txtMessage.text]]; } NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ]; NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:postURL ] ]; [ request setHTTPMethod: @"POST" ]; [ request setHTTPBody: myRequestData ]; NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self]; if (!theConnection) { UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Failed to Connect to twitter" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; } [request release]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { // release the connection, and the data object [connection release]; if(isAuthFailed){ UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Login Failed" message:@"Invalid ID/Password" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; }else{ UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Connection Failed" message:@"Failed to connect to Twitter" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; } isAuthFailed = NO; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { isAuthFailed = NO; [loading1 stopAnimating]; [loading2 stopAnimating]; if(isLogged) { UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Twitter" message:@"Tweet Posted!" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil]; [aler show]; [aler release]; txtMessage = @""; [self refresh]; } else { twitterWindow.hidden = YES; twitterWindow2.hidden = NO; [[NSNotificationCenter defaultCenter] postNotificationName:@"notifyTwitterLoggedIn" object:nil userInfo:nil]; } isLogged = YES; isLoggedIn = YES; } -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { NSDictionary* config = [NSDictionary dictionaryWithObjectsAndKeys:txtUsername.text,@"username",txtPassword.text,@"password",nil]; [config writeToFile:XAGENTS_TWITTER_CONFIG_FILE atomically:YES]; if ([challenge previousFailureCount] == 0) { NSURLCredential *newCredential; newCredential=[NSURLCredential credentialWithUser:txtUsername.text password:txtPassword.text persistence:NSURLCredentialPersistenceNone]; [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge]; } else { isAuthFailed = YES; [[challenge sender] cancelAuthenticationChallenge:challenge]; } } -(void) refresh { NSDictionary* config = [NSDictionary dictionaryWithContentsOfFile:XAGENTS_TWITTER_CONFIG_FILE]; if(config){ NSString* uname = [config valueForKey:@"username"]; if(uname){ txtUsername.text = uname; } NSString* pw = [config valueForKey:@"password"]; if(pw){ txtPassword.text = pw; } } } + (TwitterController*)defaultAgent{ if(!agent){ agent = [TwitterController new]; } return agent; } -(void)dealloc { [super dealloc]; [txtMessage release]; [txtUsername release]; [txtPassword release]; [lblId release]; [lblPassword release]; [lblURL release]; [twitterWindow2 release]; [twitterWindow release]; } @end

    Read the article

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