Every time I try and open an image within an App I get the following errors:
Here is my header file:
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import <dispatch/dispatch.h>
@interface ImageViewController : UIViewController<NSURLConnectionDataDelegate>{
dispatch_queue_t background;
}
@property (nonatomic,strong) PFObject *message;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic,strong) NSMutableData *imageData;
@property (nonatomic,strong) NSURLConnection *connection;
- (IBAction)save:(id)sender;
@end
Here is the implementation:
#import "ImageViewController.h"
@interface ImageViewController ()
@end
@implementation ImageViewController
- (void)viewDidLoad
{
NSLog(@"ImageViewController starts here");
[super viewDidLoad];
PFFile *imageFile = [self.message objectForKey:@"imageFile"];
NSURL *imageURL = [[NSURL alloc]initWithString:imageFile.url];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:imageURL];
self.connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
[self.connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
[self.connection start];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (self.imageData == nil){
self.imageData = [[NSMutableData alloc]init];
[self.imageData appendData:data];
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.imageView.image = [UIImage imageWithData:self.imageData];
}
@end
You're not actually appending anything but the initial chunk to the imageData object right now, hence the corrupt PNG.
Change this
if (self.imageData == nil){
self.imageData = [[NSMutableData alloc]init];
[self.imageData appendData:data];
}
To this
if (self.imageData == nil){
self.imageData = [[NSMutableData alloc]init];
}
[self.imageData appendData:data]; // <-- moved outside conditional