How to Multiple UIImages cropping and saving in a single loop - ios

In my project is using maximum 60 images and One of my feature is needs to be an automatically crop all the 60 images in a given Ratio. I'm using the for loop for this implementation.
Inside the for loop contains crop and save the images. It was Implemented. But My app Meets crash in device because of Due to Memory pressure. Please Help Me
for (int ref=0; ref<[_selectedPhotosCollectionthumb count];ref++)
{
UIScrollView *scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0,biManager.screenSize.height/2,biManager.screenSize.width,biManager.screenSize.height/2)];
[scrollView setDelegate:self];
[scrollView setBackgroundColor:[UIColor clearColor]];
[self addSubview:scrollView];
// scrollView.backgroundColor=[UIColor blueColor];
scrollView.userInteractionEnabled=YES;
scrollView.scrollEnabled=YES;
scrollView.tag=ref;
scrollView.hidden=YES;
[_scrollViews addObject:scrollView];
NSLog(#"%i",[_selectedPhotosCollection count]);
NSMutableArray *arrayCell=[_productCollectionsDict valueForKey:[_selectedPhotosCollection objectAtIndex:ref]];
int heightV=0;
for (int cellIndex=0;cellIndex<[arrayCell count];cellIndex++)
{
PrintCellView *cellObj=[arrayCell objectAtIndex:cellIndex];
if(cellObj.pCount>0)
{
PrintEditCellView *cell;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
cell=[[PrintEditCellView alloc] initWithFrame:CGRectMake(0,heightV*100,biManager.screenSize.width,100)];
scrollView.contentSize=CGSizeMake(0,heightV*100+100);
cell.delegate=self;
}
else
{
cell=[[PrintEditCellView alloc] initWithFrame:CGRectMake(0,heightV*50,biManager.screenSize.width,50)];
scrollView.contentSize=CGSizeMake(0,heightV*50+50);
cell.delegate=self;
}
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"hh:mm:ss";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSLog(#"The Current Time is %#",[dateFormatter stringFromDate:now]);
// NSData *imageData=UIImageJPEGRepresentation(Thumbimage,1.0);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:[_selectedPhotosCollection objectAtIndex:ref]];
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:path];
UIImage *image1=[[UIImage alloc]initWithData:data];
cell.productName.text=cellObj.productName.text;
UIImage * image=[self imageByCropping:image1 CropRatio:cell.productName.text];
NSLog(#"CROPPPP");
NSData *imageData= [[NSData alloc] initWithData:UIImageJPEGRepresentation(image,1.0)];
//
NSString* path1 = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"Prydex%i%#.jpg",cellIndex,[dateFormatter stringFromDate:now]]];
NSLog(#"pthhh:%#",path1);
[imageData writeToFile:path1 atomically:YES];
cell.editedImageURL=path1;
NSLog(#"%#,%i",cellObj.productName.text,cellObj.pCount);
[scrollView addSubview:cell];
[cell release];
heightV=heightV+1;
[dateFormatter release];
[image1 release];
// [imageData release];
// [image release];
}
}
//NSLog(#"Scroll Count %i",[_scrollViews count]);
for (UIScrollView *scrollView in _scrollViews)
{
if (scrollView.tag==0)
{
scrollView.hidden=NO;
}
else
{
scrollView.hidden=YES;
}
}
[SVProgressHUD dismiss];
}
Cropping Code
- (UIImage *)imageByCropping:(UIImage *)image CropRatio:(NSString*)ratio
{
CGSize size;
NSArray *array=[ratio componentsSeparatedByString:#"*"];
NSString *productWidth=[array objectAtIndex:0];
NSString *productHeight=[array objectAtIndex:1];
NSLog(#"SIZE:%#,%#",productWidth,productHeight);
NSLog(#"SIZE:%f,%f",image.size.width,image.size.height);
if (image.size.width/[productWidth intValue]>=230)
{
if (image.size.height/[productHeight intValue]>=230) {
size=CGSizeMake([productWidth intValue]*230,[productHeight intValue]*230);
NSLog(#"SIZE Inner:%i,%i",[productWidth intValue],[productHeight intValue]);
}
else if(image.size.width/[productWidth intValue]>=100)
{
if (image.size.height/[productHeight intValue]>=100)
{
size=CGSizeMake([productWidth intValue]*100,[productHeight intValue]*100);
NSLog(#"SIZE outer:%i,%i",[productWidth intValue],[productHeight intValue] );
}
}
}
else if(image.size.width/[productWidth intValue]>=100)
{
if (image.size.height/[productHeight intValue]>=100)
{
size=CGSizeMake([productWidth intValue]*100,[productHeight intValue]*100);
NSLog(#"SIZE outer:%i,%i",[productWidth intValue],[productHeight intValue] );
}
}
NSLog(#"crop---->%#",NSStringFromCGSize(size));
double x = (image.size.width - size.width) / 2.0;
double y = (image.size.height - size.height) / 2.0;
CGRect cropRect = CGRectMake(x, y, size.width, size.height);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}

The solution might be using recursion:
Create a method that takes an array of images you need to process. Inside the method check if array count is zero.
If it is empty you should return, possibly doing some callback to notify the application your image processing is done.
If the array is not empty, take the first image from the array, do all the processing, then remove the first object from the array and call the same method with the new array missing that element. The call should be kind of
[self performSelector:#selector(methodName:) withObject:imageArray];
All together should look something like this:
- (void)processImages:(NSArray *)images {
if(images.count < 1) {
[self performSelectorOnMainThread:#selector(imageProcessingDone) withObject:nil waitUntilDone:NO];
}
else {
UIImage *toProcess = images[0];
NSMutableArray *newArray = [images mutableCopy];
[newArray removeObjectAtIndex:0];
//do the processing
[self performSelector:#selector(processImages:) withObject:newArray];
}
}

Related

iOS Creating video from images and get EXC_BAD_ACCESS for second try

I'm making an app what makes video from images.
Here I make a new array:
self.imageList = [NSMutableArray<UIImage *> new];
And then add lots of images to this array.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
for (NSString *framePath in _effect.framePathList)
{
#autoreleasepool
{
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,framePath];
UIImage *frame = [[UIImage alloc] initWithContentsOfFile:filePath];
i++;
self.selectedEffect.image = [self applyEffect:frame];
CGRect rect = [_backgroundView bounds];
UIGraphicsBeginImageContextWithOptions(rect.size,NO,0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.backgroundView.layer renderInContext:context];
UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (capturedImage.scale * capturedImage.size.height > 640)
{
CGSize newSize = CGSizeMake(640, 640);
UIGraphicsBeginImageContext(newSize);
[capturedImage drawInRect:CGRectMake(0, 0, newSize.height, newSize.height)];
UIImage *destImage = UIGraphicsGetImageFromCurrentImageContext();
capturedImage = destImage;
destImage = nil;
UIGraphicsEndImageContext();
}
dispatch_sync(dispatch_get_main_queue(), ^
{
if (self.updateLoadingState)
{
self.updateLoadingState((float)i / framaCount * 100.0);
}
});
if (capturedImage)
{
[_imageList addObject:capturedImage];
}
}
}
Then try to create the video. Here are the methods
[self.movieMaker createMovieFromImages:_imageList withCompletion:^(NSURL *fileURL)
{
{
if (_finishBlock)
{
_finishBlock();
}
}
}];
This method is in the movieMaker class.
- (void) createMovieFromSource:(NSArray *)images extractor:(CEMovieMakerUIImageExtractor)extractor withCompletion:(CEMovieMakerCompletion)completion {self.completionBlock = completion;
[self.assetWriter startWriting];
[self.assetWriter startSessionAtSourceTime:kCMTimeZero];
dispatch_queue_t mediaInputQueue = dispatch_queue_create("mediaInputQueue", NULL);
__block NSInteger i = 0;
NSInteger frameNumber = [images count];
[self.writerInput requestMediaDataWhenReadyOnQueue:mediaInputQueue usingBlock:^{
while (YES)
{
#autoreleasepool
{
if (i >= frameNumber)
{
break;
}
if ([self.writerInput isReadyForMoreMediaData])
{
CVPixelBufferRef sampleBuffer;
NSMutableArray *test = [NSMutableArray arrayWithArray:images];
UIImage *img = extractor([test objectAtIndex:i]);
if (img == nil) {
i++;
NSLog(#"Warning: could not extract one of the frames");
continue;
}
CGImageRef img2 = [img CGImage];
sampleBuffer = [self newPixelBufferFromCGImage:img2];
CGImageRelease(img2);
if (sampleBuffer) {
if (i == 0)
{
[self.bufferAdapter appendPixelBuffer:sampleBuffer withPresentationTime:kCMTimeZero];
}
else
{
CMTime lastTime = CMTimeMake(i-1, self.frameTime.timescale);
CMTime presentTime = CMTimeAdd(lastTime, self.frameTime);
[self.bufferAdapter appendPixelBuffer:sampleBuffer withPresentationTime:presentTime];
}
CFRelease(sampleBuffer);
i++;
}
}
}
}
[self.writerInput markAsFinished];
[self.assetWriter finishWritingWithCompletionHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
self.completionBlock(self.fileURL);
});
}];
CVPixelBufferPoolRelease(self.bufferAdapter.pixelBufferPool);
}];
}
Without the CGImageRelease(img2); everything working but I have a huge memory leak. I have more then 100 images in the array. If I use CGImageRelease(img2); the first run is ok no memory leak. But If I try it again I get EXC_BAD_ACCESS in this line: self.imageList = [NSMutableArray<UIImage *> new];
Here is the error
What can I do? Thanks in advance!

How to zoom and swipe multiple images coming from webservise in objective c

1) In my application, I want to zoom and pinch an image. In xib file, there is a imageView inside a scrollview.Page control is used for swiping images. For a single image it gets zoomed, but for multiple images(coming from web service) it is not getting swipe and zoom.
In setMultipleImages method, images are not getting zoomed and swiped, while if image is single it gets zoom properly.
2) In UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]]; line code, want to replace uiimage with uiimageview. How can I do it?
My code is:
-(void)setMultipleImages{
for (int i = 0; i < [imageMArray count]; i++){
NSString *logoName;
NSArray *imageNameArray = [[imageMArray objectAtIndex:i] componentsSeparatedByString:#"/"];
logoName = [[NSString alloc]initWithFormat:#"%#",[imageNameArray lastObject]];
if (![[AppDelegateHelper getInstance] fileExist:logoName])
{
NSString *imageURL = [[NSString alloc]initWithFormat:#"%#%#",[UrlBuilder getWebsiteUrl],[imageMArray objectAtIndex:i]];
[self startProcessing];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];
[activityIndicator stopAnimating];
DebugLog(#"%f,%f",image.size.width,image.size.height);
NSArray *docDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cacheDirectory = [docDir objectAtIndex:0];
DebugLog(#"saving png");
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#",cacheDirectory,[imageNameArray lastObject]];
NSData *data1 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[data1 writeToFile:pngFilePath atomically:YES];
}
}
[self loadImageData];
}
-(void)loadImageData
{
int X =0;
for (int s=0; s<imageMArray.count; s++) {
NSString *logoName;
NSArray *imageNameArray = [[imageMArray objectAtIndex:s] componentsSeparatedByString:#"/"];
logoName = [[NSString alloc]initWithFormat:#"%#",[imageNameArray lastObject]];
if([[AppDelegateHelper getInstance] loadImage:logoName] != nil)
{
// UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(X, 0, scrollView.frame.size.width, 300)] ;
[imageView setImage:[[AppDelegateHelper getInstance] loadImage:logoName]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[scrollView addSubview: imageView];
X = X + imageView.frame.size.width;
}
else
{
//UIImageView *imageView = [[UIImageView alloc] initWithFrame: CGRectMake(X, 0, scrollView.frame.size.width, 300)] ;
[imageView setImage:[UIImage imageNamed:#"NoImage.png"]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[scrollView addSubview: imageView];
X = X + imageView.frame.size.width;
}
}
self.pageControl.numberOfPages = [imageMArray count];
scrollView.contentSize = CGSizeMake(X,scrollView.frame.size.height);
lblCount.text = [[NSString alloc]initWithFormat:#"1 sur %lu",(unsigned long)imageMArray.count];
}
Add all your images to imageview. Then apply pinchguesture to images view for zoom effect.
Pinch Guesture:
UIPinchGestureRecognizer *imageviewguesture=[[UIPinchGestureRecognizer alloc]initWithTarget:self action:#selector(ImageViewPinchGuesture:)];
add pinch guesture to your image view:
[YourImageView addGestureRecognizer:imageviewguesture];
Make your selector method:
-(void)ImageViewPinchGuesture:(UIPinchGestureRecognizer *)pinGuestureregonizer{
pinGuestureregonizer.view.transform = CGAffineTransformScale(pinGuestureregonizer.view.transform, pinGuestureregonizer.scale, pinGuestureregonizer.scale);
pinGuestureregonizer.scale = 1;
}
In your .h file add this line
-(void)ImageViewPinchGuesture:(UIPinchGestureRecognizer *)pinGuestureregonizer;
To check effect in simulator Press Cmd+alt then press left mouse pad button and drag.
Hope this will Help. Don't forget to accept the answer if it helps you.

MBProgressHUD not updating progress

I am importing multiple photos from photos library and I want to show the progress using MBProgressHUD. I am using QBImagePickerController to import photos. My photos are imported successfully. However the progress bar in MBProgressHUD is not updating. The following is my code
-(void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets {
if (imagePickerController.filterType == QBImagePickerControllerFilterTypePhotos) {
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];]
// Set the determinate mode to show task progress.
hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
hud.delegate = self;
hud.labelText = NSLocalizedString(#"Importing Photos", nil);
hud.dimBackground = YES;
hud.detailsLabelFont = [UIFont systemFontOfSize:12.0f];
hud.detailsLabelText = NSLocalizedString(#"Please wait...", nil);
hud.progress = 0.0f;
[self importPhotosForArray:assets];
}
[self dismissImagePickerController];
}
- (void) importPhotosForArray:(NSArray *)info {
for (ALAsset *selectedImageAsset in info) {
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary assetForURL:[selectedImageAsset defaultRepresentation].url resultBlock: ^(ALAsset *asset){
ALAssetRepresentation *representation = [asset defaultRepresentation];
CGImageRef imageRef = [representation fullResolutionImage];
if (imageRef) {
UIImage *image = [UIImage imageWithCGImage:imageRef];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
// Create a file name for the image
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *imageName = [NSString stringWithFormat:#"photo-%#.png", [dateFormatter stringFromDate:[NSDate date]]];
// Now we get the full path to the file
NSString *fullPathToFile = [self.folder.fullPath stringByAppendingPathComponent:imageName];
// Write out the data.
[imageData writeToFile:fullPathToFile atomically:NO];
sleep(1.0);
progress = ++index/[info count];
[MBProgressHUD HUDForView:self.navigationController.view].progress = progress;
if (progress >= 1.0) {
[[MBProgressHUD HUDForView:self.navigationController.view] hide:YES];
[self reloadData];
}
}
} failureBlock: ^(NSError *error){
// Handle failure.
NSLog(#"Failure");
}];
}
}
declare MBProgressHUD As property and use it every where.
#property (nonatomic, strong) MBProgressHUD *hud;
-(void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets {
if (imagePickerController.filterType == QBImagePickerControllerFilterTypePhotos) {
self.hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];]
// Set the determinate mode to show task progress.
self.hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
self.hud.delegate = self;
self.hud.labelText = NSLocalizedString(#"Importing Photos", nil);
self.hud.dimBackground = YES;
self.hud.detailsLabelFont = [UIFont systemFontOfSize:12.0f];
self.hud.detailsLabelText = NSLocalizedString(#"Please wait...", nil);
self.hud.progress = 0.0f;
[self importPhotosForArray:assets];
}
[self dismissImagePickerController];
}
- (void) importPhotosForArray:(NSArray *)info {
for (ALAsset *selectedImageAsset in info) {
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary assetForURL:[selectedImageAsset defaultRepresentation].url resultBlock: ^(ALAsset *asset){
ALAssetRepresentation *representation = [asset defaultRepresentation];
CGImageRef imageRef = [representation fullResolutionImage];
if (imageRef) {
UIImage *image = [UIImage imageWithCGImage:imageRef];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
// Create a file name for the image
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *imageName = [NSString stringWithFormat:#"photo-%#.png", [dateFormatter stringFromDate:[NSDate date]]];
// Now we get the full path to the file
NSString *fullPathToFile = [self.folder.fullPath stringByAppendingPathComponent:imageName];
// Write out the data.
[imageData writeToFile:fullPathToFile atomically:NO];
sleep(1.0);
progress = ++index/[info count];
self.hud.progress = progress;
if (progress >= 1.0) {
[MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
[self reloadData];
}
}
} failureBlock: ^(NSError *error){
// Handle failure.
NSLog(#"Failure");
}];
}
}
Try this
Because as per your code when u update progress every time new object of MBProgressHUD get and update
UI updates (i.e. changes to the progress bar) must be made on the main thread or you may suffer from unpredictable side effects.
The user interface element may not be redrawn after your property changes
I believe that ALAssetsLibrary.assetForURL is automatically happening in a background thread. To get around that you want to use a solution that lets you run the UI updates on the main thread. In this case your UI updates would be this line
[MBProgressHUD HUDForView:self.navigationController.view].progress = progress;
so try something like this:
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD HUDForView:self.navigationController.view].progress = progress;
});
Also, you should verify that ++index/[info count] is actually increasing as you expect it to by printing the value out each time index updates.
Try this code. Replace your importPhotosForArray method with the following.
- (void) importPhotosForArray:(NSArray *)info {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
__block float progress = 0.0f;
__block float index = 0.0f;
for (ALAsset *selectedImageAsset in info) {
ALAssetRepresentation *representation = [selectedImageAsset defaultRepresentation];
CGImageRef imageRef = [representation fullResolutionImage];
if (imageRef) {
UIImage *image = [UIImage imageWithCGImage:imageRef];
NSData *imageData = UIImagePNGRepresentation(image);
// Create a file name for the image
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *imageName = [NSString stringWithFormat:#"photo-%#.png", [dateFormatter stringFromDate:[NSDate date]]];
// Now we get the full path to the file
NSString *fullPathToFile = [self.folder.fullPath stringByAppendingPathComponent:imageName];
// Write out the data.
[imageData writeToFile:fullPathToFile atomically:YES];
sleep(1);
progress = ++index/[info count];
dispatch_async(dispatch_get_main_queue(), ^{
// Instead we could have also passed a reference to the HUD
// to the HUD to myProgressTask as a method parameter.
[MBProgressHUD HUDForView:self.navigationController.view].progress = progress;
});
if (progress >= 1.0) {
dispatch_async(dispatch_get_main_queue(), ^{
// Instead we could have also passed a reference to the HUD
// to the HUD to myProgressTask as a method parameter.
[[MBProgressHUD HUDForView:self.navigationController.view] hide:YES];
[self reloadData];
});
}
}
}
});
}

How to implement endless loading in table or collection view?

I’m building an article reading app. I’m fetching data from JSON link like article image and title in uitableview.
I’m unable to implement pagination in uitableview, let say my JSON link is www.example.com&page=1 contain 10 articles at a time which is 1-10.
When I concatenate in the JSON link like www.example.com&page=2 to get 11-20 article list.
I’m unable to implement how I can load the data in uitableview on scrolling and increase no.of rows with data.
Here is my code:
int *x=1;
int *inc=10;
#interface ysTableViewController ()
{
Reachability *internetReachable;
}
#end
#implementation ysTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self checkInternetConnection];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,10,0,20)];
titleLabel.textColor = [UIColor blackColor];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.text = #"Story";
[self.navigationItem setTitleView:titleLabel];
}
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
CGPoint offset = aScrollView.contentOffset;
CGRect bounds = aScrollView.bounds;
CGSize size = aScrollView.contentSize;
UIEdgeInsets inset = aScrollView.contentInset;
float y = offset.y + bounds.size.height - inset.bottom;
float h = size.height;
float reload_distance = 10;
if(y > h + reload_distance) {
NSLog(#"load more rows");
inc=inc+10;
BOOL myBool = [self isNetworkAvailable];
if (myBool)
{
#try {
// for table cell seperator line color
self.tableView.separatorColor = [UIColor colorWithRed:190/255.0 green:190/255.0 blue:190/255.0 alpha:1.0];
// for displaying the previous screen lable with back button in details view controller
UIBarButtonItem *backbutton1 = [[UIBarButtonItem alloc] initWithTitle:#"" style:UIBarButtonItemStyleBordered target:nil action:nil];
[[self navigationItem] setBackBarButtonItem:backbutton1];
_Title1 = [[NSMutableArray alloc] init];
_Author1 = [[NSMutableArray alloc] init];
_Images1 = [[NSMutableArray alloc] init];
_Details1 = [[NSMutableArray alloc] init];
_link1 = [[NSMutableArray alloc] init];
_Date1 = [[NSMutableArray alloc] init];
NSString *urlString=[NSString stringWithFormat:#“www.example.com&page=%d",x];
NSLog(#"xxxxx===%d",x);
NSURL *newUrl=[NSURL URLWithString:urlString];
NSData* data = [NSData dataWithContentsOfURL:newUrl];
NSArray *ys_avatars = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
x++;
if(ys_avatars){
for (int j=0;j<ys_avatars.count;j++)
{
[_Title1 addObject:ys_avatars[j][#"title"]];
[_Author1 addObject: ys_avatars[j][#"author"]];
[_Images1 addObject: ys_avatars[j][#"featured_img"]];
[_Details1 addObject:ys_avatars[j][#"content"]];
[_link1 addObject:ys_avatars[j][#"permalink"]];
NSString *newStr=[ys_avatars[j][#"date"] substringToIndex:[ys_avatars[j][#"date"] length]-3];
[_Date1 addObject:newStr];
} }
else
{
NSLog(#"asd");
} }
#catch (NSException *exception) {
}
}
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return inc;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *Cellidentifier1 = #"ysTableViewCell";
ysTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:Cellidentifier1 forIndexPath:indexPath];
// Configure the cell...
long row = [indexPath row];
cell1.TitleLabel1.text = _Title1[row];
cell1.AuthorLabel1.text = _Author1[row];
NSString *yourStoryUrl = [_Images1[indexPath.row] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
if(yourStoryUrl) {
NSArray *subStringsUrl = [yourStoryUrl componentsSeparatedByString:#"/"];
NSString *stripedName = [subStringsUrl lastObject];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//Local stored image file path
NSString* filePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",stripedName]];
if(filePath) {
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
if(image) {
// Now the image will have been loaded and decoded and is ready to rock for the main thread
ysTableViewCell *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath];
if(updateCell)
updateCell.ThumbImage1.image=image;
cell1.ThumbImage1.image=image;
} else {
dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(taskQ, ^{
NSURL *Imageurl = [NSURL URLWithString:yourStoryUrl];
NSData *data = [NSData dataWithContentsOfURL:Imageurl];
UIImage *images1 = [[UIImage alloc] initWithData:data];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSData *imageData = UIImagePNGRepresentation(images1);
//_imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",stripedName]];
// NSLog((#"pre writing to file"));
if (![imageData writeToFile:filePath atomically:NO])
{
NSLog((#"Failed to cache image data to disk"));
}
else
{
NSLog((#"the cachedImagedPath is %#",filePath));
}
// Now the image will have been loaded and decoded and is ready to rock for the main thread
dispatch_sync(dispatch_get_main_queue(), ^{
ysTableViewCell *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath];
if(updateCell)
updateCell.ThumbImage1.image=images1;
cell1.ThumbImage1.image=images1;
});
});
}
} else {
dispatch_queue_t taskQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(taskQ, ^{
NSURL *Imageurl = [NSURL URLWithString:yourStoryUrl];
NSData *data = [NSData dataWithContentsOfURL:Imageurl];
UIImage *images1 = [[UIImage alloc] initWithData:data];
// NSString *myString = [Imageurl absoluteString];
// NSLog(#"%#",myString);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSData *imageData = UIImagePNGRepresentation(images1);
_imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png",stripedName]];
// NSLog((#"pre writing to file"));
if (![imageData writeToFile:_imagePath atomically:NO])
{
NSLog((#"Failed to cache image data to disk"));
}
else
{
// NSLog((#"the cachedImagedPath is %#",_imagePath));
}
// Now the image will have been loaded and decoded and is ready to rock for the main thread
dispatch_sync(dispatch_get_main_queue(), ^{
ysTableViewCell *updateCell =(id)[tableView cellForRowAtIndexPath:indexPath];
if(updateCell)
updateCell.ThumbImage1.image=images1;
cell1.ThumbImage1.image=images1;
});
});
}
}
return cell1;
}
This is by no means easy. IN GENERAL TERMS you need code that looks like this..
Note the four very distinct parts of this fundamental routine.
I have never found a working "general" package solution for this problem.
Again, look to the "four sections" in this: they give the logic you're looking for!
-(void)forTerm:(NSString *)term doPageAfter:(int)doingThisPage
{
doingThisPage = doingThisPage + 1;
if ( doingThisPage > 20 ) return; // never, ever, ever forget that!! heh.
[CLOUD search:term page:doingThisPage then:^(NSArray *thoseTenResults)
{
self.searchSpinner.hidden = YES;
// (step 1) IF IT IS "PAGE 1", we need to re-kick-off the array...
if ( doingThisPage == 1 )
CLOUD.searchResultsRA = [[NSMutableArray alloc] init];
// (step 2) go ahead and add on these results
if ( doingThisPage == 1 )
{
[CLOUD.searchResultsRA addObjectsFromArray:thoseTenResults];
[self.searchDisplay safelyReloadBouncyTable];
}
else
{
[self.searchDisplay.collectionView performBatchUpdates:^
{
NSUInteger oldSize = CLOUD.searchResultsRA.count;
[CLOUD.searchResultsRA addObjectsFromArray:thoseTenResults];
NSUInteger newSize = CLOUD.searchResultsRA.count;
NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
for (NSUInteger i = oldSize; i < newSize; i++)
[arrayWithIndexPaths
addObject:[NSIndexPath indexPathForRow:i inSection:0]];
[self.searchDisplay justSignal];
[self.searchDisplay.collectionView
insertItemsAtIndexPaths:arrayWithIndexPaths];
}
completion:nil];
}
// (step 3) indeed if it's the first page, do a drop-in for fun
if ( doingThisPage == 1 ) [self.searchDisplay.view dropIn:nil];
// (for a "new search" which is now being displayed, in your UX
// there would be some sort of indication of that fact - do it here)
// (step 4) IF there WERE results .. try another page!
if ( thoseTenResults.count > 0 )
[self forTerm:term doPageAfter:doingThisPage];
// note we are calling this same routine, again!!!
}
];
}

UIimageView array of images fade from one image to the next bug

Hi I have some code that mostly works. It basically animates, with a fade affect, number of images from an array.
Basically it all works well however I have a slight bug that when the view first loads the first image only in the array seems to rotate 90 degrees to the correct position and then fades to the same image but its annoying to see animate like this. All the fading from image to another is perfect just with the above mentioned bug. And as mentioned is just on first load.
Here is the code. images is an MutableArray and both topImageView and bottomImageView both are ivars and ** synthesized**. So is the images array, too.
int topIndex = 0, bottomIndex = 1;
-(void)imageFader{
self.imageViewBottom = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 370)];
[self.view addSubview:imageViewBottom];
[imageViewBottom setAlpha:0.0];
[imageViewBottom release];
self.imageViewTop = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 370)];
[self.view addSubview:imageViewTop];
[imageViewTop setAlpha:1.0];
[imageViewTop release];
[imageViewTop setImage:[images objectAtIndex:topIndex]];
timer = [NSTimer timerWithTimeInterval:1.0
target:self
selector:#selector(onTimer)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[timer fire];
}
-(void)onTimer{
[UIView animateWithDuration:1 animations:^{
//set the image of the image that is not currently visible
if (imageViewTop.alpha == 0) {
[imageViewTop setImage:[images objectAtIndex:topIndex]];
}
if (imageViewBottom.alpha == 0) {
[imageViewBottom setImage:[images objectAtIndex:bottomIndex]];
}
//make sure the images rotate
[imageViewTop setAlpha:imageViewTop.alpha == 0 ? 1 : 0];
[imageViewBottom setAlpha:imageViewBottom.alpha == 0 ? 1 : 0];
//make sure the images play in a loop
topIndex = topIndex < [images count]-1 ? bottomIndex+1 : 0;
bottomIndex = bottomIndex < [images count]-1 ? bottomIndex+1 : 0;}];
}
And here is how the images are saved to the docs directory before being loaded in to the MutableArray for the animation.
-(void) imagePickerController:(UIImagePickerController *) picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
NSMutableDictionary *metadata = [[NSMutableDictionary alloc] init];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
//Save to camera roll
[library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation) ALAssetOrientationRight completionBlock:^(NSURL *assetURL, NSError *error) { NSLog(#"completionBlock");
}];
int imageNumber = 0;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathToFile;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
do
{
// increment the image
imageNumber++;
// get the new path to the file
pathToFile = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:
#"standingImage%d.JPG", imageNumber]];
}
while([fileManager fileExistsAtPath:pathToFile]);
/* so, we loop for as long as we keep coming up with names that already exist */
UIImage *image2 = image; // imageView is my image from camera
//Use UIImageJPEGRepresentation to maitain image orientation!
NSData *imageData = UIImageJPEGRepresentation(image2, 0.9);
[imageData writeToFile:pathToFile atomically:NO];
[self dismissModalViewControllerAnimated:YES];
This unexpected orientation may be caused by the origin of the images - the UIImagePickerController. Try accessing the JPEG files you mentioned in your comment and check their orientation, then you'll at least narrow down the potential cause of your issue.

Resources