Add GifHud in custom UIView - ios

I am trying to display an Activity Indicator with gif in a small view at top of screen. For this I am using this class (GifHud):
//
// GiFHUD.m
// GiFHUD
//
// Created by Cem Olcay on 30/10/14.
// Copyright (c) 2014 Cem Olcay. All rights reserved.
//
#import "GiFHUD.h"
#import "AppDelegate.h"
#import <ImageIO/ImageIO.h>
#define Size 70
#define FadeDuration 0.3
#define GifSpeed 0.3
#define APPDELEGATE ((AppDelegate*)[[UIApplication sharedApplication] delegate])
#if __has_feature(objc_arc)
#define toCF (__bridge CFTypeRef)
#define fromCF (__bridge id)
#else
#define toCF (CFTypeRef)
#define fromCF (id)
#endif
#pragma mark - UIImage Animated GIF
#implementation UIImage (animatedGIF)
static int delayCentisecondsForImageAtIndex(CGImageSourceRef const source, size_t const i) {
int delayCentiseconds = 1;
CFDictionaryRef const properties = CGImageSourceCopyPropertiesAtIndex(source, i, NULL);
if (properties) {
CFDictionaryRef const gifProperties = CFDictionaryGetValue(properties, kCGImagePropertyGIFDictionary);
if (gifProperties) {
NSNumber *number = fromCF CFDictionaryGetValue(gifProperties, kCGImagePropertyGIFUnclampedDelayTime);
if (number == NULL || [number doubleValue] == 0) {
number = fromCF CFDictionaryGetValue(gifProperties, kCGImagePropertyGIFDelayTime);
}
if ([number doubleValue] > 0) {
// Even though the GIF stores the delay as an integer number of centiseconds, ImageIO “helpfully” converts that to seconds for us.
delayCentiseconds = (int)lrint([number doubleValue] * 100);
}
}
CFRelease(properties);
}
return delayCentiseconds;
}
static void createImagesAndDelays(CGImageSourceRef source, size_t count, CGImageRef imagesOut[count], int delayCentisecondsOut[count]) {
for (size_t i = 0; i < count; ++i) {
imagesOut[i] = CGImageSourceCreateImageAtIndex(source, i, NULL);
delayCentisecondsOut[i] = delayCentisecondsForImageAtIndex(source, i);
}
}
static int sum(size_t const count, int const *const values) {
int theSum = 0;
for (size_t i = 0; i < count; ++i) {
theSum += values[i];
}
return theSum;
}
static int pairGCD(int a, int b) {
if (a < b)
return pairGCD(b, a);
while (true) {
int const r = a % b;
if (r == 0)
return b;
a = b;
b = r;
}
}
static int vectorGCD(size_t const count, int const *const values) {
int gcd = values[0];
for (size_t i = 1; i < count; ++i) {
// Note that after I process the first few elements of the vector, `gcd` will probably be smaller than any remaining element. By passing the smaller value as the second argument to `pairGCD`, I avoid making it swap the arguments.
gcd = pairGCD(values[i], gcd);
}
return gcd;
}
static NSArray *frameArray(size_t const count, CGImageRef const images[count], int const delayCentiseconds[count], int const totalDurationCentiseconds) {
int const gcd = vectorGCD(count, delayCentiseconds);
size_t const frameCount = totalDurationCentiseconds / gcd;
UIImage *frames[frameCount];
for (size_t i = 0, f = 0; i < count; ++i) {
UIImage *const frame = [UIImage imageWithCGImage:images[i]];
for (size_t j = delayCentiseconds[i] / gcd; j > 0; --j) {
frames[f++] = frame;
}
}
return [NSArray arrayWithObjects:frames count:frameCount];
}
static void releaseImages(size_t const count, CGImageRef const images[count]) {
for (size_t i = 0; i < count; ++i) {
CGImageRelease(images[i]);
}
}
static UIImage *animatedImageWithAnimatedGIFImageSource(CGImageSourceRef const source) {
size_t const count = CGImageSourceGetCount(source);
CGImageRef images[count];
int delayCentiseconds[count]; // in centiseconds
createImagesAndDelays(source, count, images, delayCentiseconds);
int const totalDurationCentiseconds = sum(count, delayCentiseconds);
NSArray *const frames = frameArray(count, images, delayCentiseconds, totalDurationCentiseconds);
UIImage *const animation = [UIImage animatedImageWithImages:frames duration:(NSTimeInterval)totalDurationCentiseconds / 100.0];
releaseImages(count, images);
return animation;
}
static UIImage *animatedImageWithAnimatedGIFReleasingImageSource(CGImageSourceRef CF_RELEASES_ARGUMENT source) {
if (source) {
UIImage *const image = animatedImageWithAnimatedGIFImageSource(source);
CFRelease(source);
return image;
} else {
return nil;
}
}
+ (UIImage *)animatedImageWithAnimatedGIFData:(NSData *)data {
return animatedImageWithAnimatedGIFReleasingImageSource(CGImageSourceCreateWithData(toCF data, NULL));
}
+ (UIImage *)animatedImageWithAnimatedGIFURL:(NSURL *)url {
return animatedImageWithAnimatedGIFReleasingImageSource(CGImageSourceCreateWithURL(toCF url, NULL));
}
#end
#pragma mark - GiFHUD Private
#interface GiFHUD ()
+ (instancetype)instance;
#property (nonatomic, strong) UIView *overlayView;
#property (nonatomic, strong) UIImageView *imageView;
#property (nonatomic, assign) BOOL shown;
#end
#pragma mark - GiFHUD Implementation
#implementation GiFHUD
#pragma mark Lifecycle
static GiFHUD *instance;
+ (instancetype)instance {
if (!instance) {
instance = [[GiFHUD alloc] init];
}
return instance;
}
- (instancetype)init {
if ((self = [super initWithFrame:CGRectMake(0, 0, Size, Size)])) {
[self setAlpha:0];
[self setCenter:APPDELEGATE.window.center];
[self setClipsToBounds:NO];
// [self.layer setBackgroundColor:[[UIColor colorWithWhite:0 alpha:0.5] CGColor]];
// [self.layer setCornerRadius:10];
// [self.layer setMasksToBounds:YES];
self.imageView = [[UIImageView alloc] initWithFrame:CGRectInset(self.bounds, 20, 20)];
[self addSubview:self.imageView];
[APPDELEGATE.window addSubview:self];
}
return self;
}
#pragma mark HUD
+ (void)showWithOverlay {
[self dismiss:^{
[APPDELEGATE.window addSubview:[[self instance] overlay]];
[self show];
}];
}
+ (void)show {
[self dismiss:^{
[APPDELEGATE.window bringSubviewToFront:[self instance]];
[[self instance] setShown:YES];
[[self instance] fadeIn];
}];
}
+ (void)dismiss {
if (![[self instance] shown])
return;
[[[self instance] overlay] removeFromSuperview];
[[self instance] fadeOut];
}
+ (void)dismiss:(void(^)(void))complated {
if (![[self instance] shown])
return complated ();
[[self instance] fadeOutComplate:^{
[[[self instance] overlay] removeFromSuperview];
complated ();
}];
}
#pragma mark Effects
- (void)fadeIn {
[self.imageView startAnimating];
[UIView animateWithDuration:FadeDuration animations:^{
[self setAlpha:1];
}];
}
- (void)fadeOut {
[UIView animateWithDuration:FadeDuration animations:^{
[self setAlpha:0];
} completion:^(BOOL finished) {
[self setShown:NO];
[self.imageView stopAnimating];
}];
}
- (void)fadeOutComplate:(void(^)(void))complated {
[UIView animateWithDuration:FadeDuration animations:^{
[self setAlpha:0];
} completion:^(BOOL finished) {
[self setShown:NO];
[self.imageView stopAnimating];
complated ();
}];
}
- (UIView *)overlay {
if (!self.overlayView) {
self.overlayView = [[UIView alloc] initWithFrame:APPDELEGATE.window.frame];
[self.overlayView setBackgroundColor:[UIColor blackColor]];
[self.overlayView setAlpha:0];
[UIView animateWithDuration:FadeDuration animations:^{
[self.overlayView setAlpha:0.3];
}];
}
return self.overlayView;
}
#pragma mark Gif
+ (void)setGifWithImages:(NSArray *)images {
[[[self instance] imageView] setAnimationImages:images];
[[[self instance] imageView] setAnimationDuration:GifSpeed];
}
+ (void)setGifWithImageName:(NSString *)imageName {
[[[self instance] imageView] stopAnimating];
[[[self instance] imageView] setImage:[UIImage animatedImageWithAnimatedGIFURL:[[NSBundle mainBundle] URLForResource:imageName withExtension:nil]]];
}
+ (void)setGifWithURL:(NSURL *)gifUrl {
[[[self instance] imageView] stopAnimating];
[[[self instance] imageView] setImage:[UIImage animatedImageWithAnimatedGIFURL:gifUrl]];
}
#end
In my custom view I am displaying GifHud as follows :
[GiFHUD setGifWithImageName:#"loader-fast-trp48.gif"];
[GiFHUD show];
This however displays the GifHud at centre of screen which I understand. But I want the Hud to appear on the custom view which is at the top of screen. How may I do this? I tried this but it gives exception :
[self addSubview:[GiFHUD self]];

- (instancetype)init {
if ((self = [super initWithFrame:CGRectMake(0, 0, Size, Size)])) {
[self setAlpha:0];
[self setCenter:CGPointMake(self.view.window.center.x, Your_HEIGHT)];
[self setClipsToBounds:NO];
//[self.layer setBackgroundColor:[[UIColor colorWithWhite:0 alpha:0.5] CGColor]];
//[self.layer setCornerRadius:10];
//[self.layer setMasksToBounds:YES];
self.imageView = [[UIImageView alloc] initWithFrame:CGRectInset(self.bounds, 20, 20)];
[self addSubview:self.imageView];
[APPDELEGATE.window addSubview:self];
}
return self;
}
Try resizing the center using [self setCenter:CGPointMake(self.view.window.center.x, Your_HEIGHT)]; in my answer. Hope this help.

Related

iOS - My app crashes with memory Error if only runs on Device

My app runs perfectly on simulator.
But when I run it on device to test, the app crashed.
The displayed error :
"malloc: * error for object 0x17415d0c0: Invalid pointer dequeued from free list * set a breakpoint in malloc_error_break to debug";
And another error sometimes happens :
"Thread 6 com.apple.NSURLConnectionLoader: Program received signal: EXC_BAD_ACCESS"
This two errors are random, it happens after the app runs two or three minutes.
I searched Google and find some solution.
It says that set a breakpoint in malloc_error_break to debug, but this only work on simulator. Even I set the malloc_error_break, the app still crush and it does not display anything, I only can see that error message.
This is big project, I really do not know which part of the code cause the problem and which part of the code I need to post.
But I have doubt with one of the class, my 'SynchroningView'.
This view will be displayed if only my app make synchronisation with the server. It means this view is included in almost all the Viewcontroller in my project.
Here is my 'SynchroningView' class:
"SynchroningView.h"
#import <UIKit/UIKit.h>
#class SynchroningView;
#protocol SynchroningViewDelegate
#optional
- (void)SynchroningViewCancelButtonDidClicked:(SynchroningView *)synchroningView;
- (void)SynchroningViewStartTherapyButtonDidClicked:(SynchroningView *)synchroningView;
#end
#interface SynchroningView : UIView <DataManagerDelegate>
#property (nonatomic, assign) id<SynchroningViewDelegate>delegateCustom;
#property (nonatomic, retain) UIButton *containerButton;
#property (nonatomic, retain) Patient *singlePatient;
- (instancetype)initWithFrame:(CGRect)frame;
- (void)showInView:(UIView *)view;
- (void)dismissMenuPopover;
#end
SynchroningView.m
#import "SDDemoItemView.h"
#import "SDPieLoopProgressView.h"
#define Directory_Document [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
#define FileName_Image_SynchroningView_BackGroundImageName #"SynchroningView_BackGroundImage"
#define FilePath_Image_SynchroningView_BackGroundImageName [Directory_Document stringByAppendingPathComponent:FileName_Image_SynchroningView_BackGroundImageName]
#interface SynchroningView ()
#property (nonatomic, strong) DataManager* dataManager;
#property (nonatomic, retain) UILabel* messageLabel;
#property (nonatomic, retain) UIButton* CancelButton;
#property (nonatomic, retain) CoolButton* ConfirmButton;
#property (nonatomic, retain) CoolButton* startTherapyButton;
#property (nonatomic, strong) SDDemoItemView* demoProgressView;
#end
#interface SynchroningView ()
{
BOOL _blinking;
NSTimer *timer;
}
#end
#implementation SynchroningView
-(void)dealloc
{
}
//get the background Image, make it blur and save it. In this way I do not have to use Blur function everytim, I use the blured image directly
- (UIImage *)getBackGroundImage
{
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:FilePath_Image_SynchroningView_BackGroundImageName]) {
return [UIImage imageWithContentsOfFile:FilePath_Image_SynchroningView_BackGroundImageName];
}
else{
UIImage *backImage = [UIImage imageWithContentsOfFile:kBackgroundImagePath];
backImage = [backImage blurWithFloat:20.0f];
NSData * binaryImageData = UIImagePNGRepresentation(backImage);
if ([binaryImageData writeToFile:FilePath_Image_SynchroningView_BackGroundImageName atomically:YES]) {
return backImage;
}
}
return [UIImage imageWithContentsOfFile:kBackgroundImagePath];
}
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_blinking = NO;
self.dataManager = [[DataManager alloc] init];
self.dataManager.DelegateCustom = self;
self.backgroundColor = [UIColor clearColor];
self.containerButton = [[UIButton alloc] init];
[self.containerButton setBackgroundColor:RGBA_Custom(0, 0, 0, 0.6f)];
[self.containerButton setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin];
UIView *shadowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
[self addSubview:shadowView];
shadowView.backgroundColor = RGBA_Custom(230, 249, 251, 0.96f);
// shadowView.layer.borderWidth = 2*IPAD;
// shadowView.layer.borderColor = [RGBA_Custom(199, 199, 199, 1.0f) CGColor];
shadowView.layer.shadowColor = [UIColor blackColor].CGColor;
shadowView.layer.shadowOpacity = 0.4;
shadowView.layer.shadowRadius = 4*IPAD;
shadowView.layer.shadowOffset = CGSizeMake(4.0f*IPAD, 4.0f*IPAD);
shadowView.layer.cornerRadius = 6*IPAD;
shadowView.userInteractionEnabled = NO;
UIImageView *backGround = [[UIImageView alloc] initWithImage:[self getBackGroundImage]];
backGround.frame = CGRectMake(0, 0, shadowView.frame.size.width, shadowView.frame.size.height);
backGround.backgroundColor = [UIColor clearColor];
[shadowView addSubview:backGround];
backGround.layer.cornerRadius = shadowView.layer.cornerRadius;
backGround.layer.masksToBounds = YES;
ImageWIDTH_ = self.frame.size.height*0.3;
self.demoProgressView =[SDDemoItemView demoItemViewWithClass:[SDPieLoopProgressView class]];
self.demoProgressView.frame = CGRectMake((self.frame.size.width - ImageWIDTH_)/2,
kFromLeft,
ImageWIDTH_,
ImageWIDTH_);
[self addSubview:self.demoProgressView];
self.messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(kFromLeft,
self.demoProgressView.frame.origin.y + self.demoProgressView.frame.size.height + kFromLeft,
self.frame.size.width - kFromLeft*2,
self.frame.size.height - (self.demoProgressView.frame.origin.y + self.demoProgressView.frame.size.height + kFromLeft*2))];
self.messageLabel.backgroundColor = [UIColor clearColor];
self.messageLabel.textColor = [UIColor blackColor];
self.messageLabel.textAlignment = NSTextAlignmentCenter;
self.messageLabel.numberOfLines = 0;
self.messageLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.messageLabel.font = [UIFont boldSystemFontOfSize:kIPAD ? 20:12];
self.messageLabel.text = #"";
self.messageLabel.adjustsFontSizeToFitWidth = YES;
[self addSubview:self.messageLabel];
CGFloat BtnHeight = kIPAD ? 40 : 30;
self.CancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.CancelButton.frame = CGRectMake(self.frame.size.width - kFromLeft*0.5 - BtnHeight,
kFromLeft*0.5,
BtnHeight,
BtnHeight);
self.CancelButton.backgroundColor = [UIColor clearColor];
[self.CancelButton setImage:[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"utilities_close" ofType:#"png"]] forState:UIControlStateNormal];
[self.CancelButton addTarget:self action:#selector(pressCancelButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.CancelButton];
BtnHeight = kIPAD ? 70 : 50;
CGFloat BtnWidth = self.frame.size.width/4;
NSString* ConfirmButtonStr = NSLocalizedString(#"Confirm", nil);
ExpectedSize = [ConfirmButtonStr sizeWithFont:self.messageLabel.font constrainedToSize:CGSizeMake(VIEW_WIDTH, BtnHeight) lineBreakMode:NSLineBreakByWordWrapping];
ExpectedSize = CGSizeMake(ExpectedSize.width + 30*IPAD, ExpectedSize.height);
self.ConfirmButton = [CoolButton buttonWithType:UIButtonTypeCustom];
self.ConfirmButton.frame = CGRectMake((self.frame.size.width - ExpectedSize.width)/2,
self.frame.size.height - BtnHeight - kFromLeft,
ExpectedSize.width,
BtnHeight);
self.ConfirmButton.titleLabel.font = self.messageLabel.font;
[self.ConfirmButton setTitle:ConfirmButtonStr forState:UIControlStateNormal];
[self.ConfirmButton addTarget:self action:#selector(pressConfirmButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.ConfirmButton];
BtnWidth = self.frame.size.width*0.6;
NSString* startTherapyButtonStr = NSLocalizedString(#"StartTerapia", nil);
ExpectedSize = [startTherapyButtonStr sizeWithFont:self.messageLabel.font constrainedToSize:CGSizeMake(VIEW_WIDTH, BtnHeight) lineBreakMode:NSLineBreakByWordWrapping];
ExpectedSize = CGSizeMake(ExpectedSize.width + 30*IPAD, ExpectedSize.height);
self.startTherapyButton = [CoolButton buttonWithType:UIButtonTypeCustom];
self.startTherapyButton.frame = CGRectMake((self.frame.size.width - ExpectedSize.width)/2,
self.ConfirmButton.frame.origin.y,
ExpectedSize.width,
self.ConfirmButton.frame.size.height);
self.startTherapyButton.titleLabel.font = self.messageLabel.font;
[self.startTherapyButton setTitle:startTherapyButtonStr forState:UIControlStateNormal];
[self.startTherapyButton addTarget:self action:#selector(startTherapyButtonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.startTherapyButton];
self.CancelButton.alpha = 0.0;
self.ConfirmButton.alpha = 0.0;
self.startTherapyButton.alpha = 0.0;
if (self.dataManager.firstSynchronizationAgain == 1 && [AccessedInfo getAccessedInfo]) {
UILabel *alertInfoLabel = [[UILabel alloc] initWithFrame:CGRectMake(kFromLeft,
0,
self.frame.size.width - kFromLeft*2,
VIEW_HEIGHT)];
alertInfoLabel.backgroundColor = [UIColor clearColor];
alertInfoLabel.textColor = COLOR_CIRCLE;
alertInfoLabel.textAlignment = NSTextAlignmentCenter;
alertInfoLabel.numberOfLines = 0;
alertInfoLabel.lineBreakMode = NSLineBreakByWordWrapping;
alertInfoLabel.font = [UIFont systemFontOfSize:self.startTherapyButton.titleLabel.font.pointSize-2];
alertInfoLabel.text = NSLocalizedString(#"SynchronizingNew", nil);
ExpectedSize = [alertInfoLabel.text sizeWithFont:alertInfoLabel.font constrainedToSize:alertInfoLabel.frame.size lineBreakMode:NSLineBreakByWordWrapping];
alertInfoLabel.frame = CGRectMake(alertInfoLabel.frame.origin.x,
self.startTherapyButton.frame.origin.y - ExpectedSize.height - IPAD*2,
alertInfoLabel.frame.size.width,
ExpectedSize.height);
[self addSubview:alertInfoLabel];
}
[self.containerButton addSubview:self];
}
return self;
}
//show the synchronization result message
- (void)setMessageLabelString:(NSString *)labelName
{
self.messageLabel.text = labelName;
ExpectedSize = [labelName sizeWithFont:self.messageLabel.font constrainedToSize:CGSizeMake(self.messageLabel.frame.size.width, VIEW_HEIGHT) lineBreakMode:NSLineBreakByWordWrapping];
self.messageLabel.frame = CGRectMake(self.messageLabel.frame.origin.x,
self.messageLabel.frame.origin.y,
self.messageLabel.frame.size.width,
ExpectedSize.height);
timer = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:#selector(MessageLabelBlinking) userInfo:nil repeats:YES];
// self.messageLabel.adjustsFontSizeToFitWidth = YES;
}
- (void)MessageLabelBlinking
{
if (_blinking) {
NSString *threeDot = #".....";
if ([self.messageLabel.text rangeOfString:threeDot].location == NSNotFound) {
self.messageLabel.text = [self.messageLabel.text stringByAppendingString:#"."];
}
else{
self.messageLabel.text = [self.messageLabel.text stringByReplacingOccurrencesOfString:threeDot withString:#""];
}
}
else{
[timer invalidate];
timer = nil;
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
//init the data processing block
- (void)initCustomOtherParameters
{
self.dataManager.DelegateCustom = self;
self.dataManager.blockProcessingData = ^(float allCommand, float restCommand){
if (allCommand == 0) {
[[SingletonOperationQueue mainQueue] addOperationWithBlock:^{
self.demoProgressView.progressView.progress = 1;
NSString *messageStr = [NSLocalizedString(#"SuccessfulSynchronized", nil) stringByAppendingFormat:#"\n%#", NSLocalizedString(#"EmptyTherapy", nil)];
[self setMessageLabelString:messageStr];
_blinking = NO;
self.CancelButton.alpha = 1.0;
}];
}
else{
float percenAger = (restCommand/allCommand);
percenAger = 1 - percenAger;
[[SingletonOperationQueue mainQueue] addOperationWithBlock:^{
self.demoProgressView.progressView.progress = percenAger;
if (restCommand == 0) {
[self downloadZipFile];
}
}];
}
};
[Patient RemovePatient];
[self.singlePatient SavePatient];
}
- (void)showInView:(UIView *)view
{
self.transform = CGAffineTransformScale(self.transform, 0.8, 0.8);
self.containerButton.alpha = 0.0f;
self.containerButton.frame = view.bounds;
[view addSubview:self.containerButton];
[UIView animateWithDuration:0.15 animations:^{
self.containerButton.alpha = 1.0f;
self.transform = CGAffineTransformScale(self.transform, 1.4, 1.4);
}completion:^(BOOL finished) {
if (finished) {
[UIView animateWithDuration:0.20 animations:^{
self.transform = CGAffineTransformIdentity;
}];
[self sendConnectionTestRequest];
}
else{
self.transform = CGAffineTransformIdentity;
[self sendConnectionTestRequest];
}
}];
}
- (void)dismissMenuPopover
{
[self hide];
}
- (void)hide
{
[UIView animateWithDuration:0.25 animations:^{
self.transform = CGAffineTransformScale(self.transform, 0.8, 0.8);
self.containerButton.alpha = 0.0f;
}completion:^(BOOL finished) {
if (finished) {
[self.containerButton removeFromSuperview];
}
}];
}
- (void)pressCancelButton:(UIButton *)button
{
[self.dataManager CommunicationCancel];
[self.delegateCustom SynchroningViewCancelButtonDidClicked:self];
}
- (void)startTherapyButtonDidClicked:(UIButton *)button
{
[self.delegateCustom SynchroningViewStartTherapyButtonDidClicked:self];
}
- (void)pressConfirmButton:(UIButton *)button
{
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 0.0;
self.ConfirmButton.alpha = 0.0;
}];
[self sendRegistrationRequestConfirm:YES];
}
#pragma mark - Communication
- (void)sendConnectionTestRequest
{
[self initCustomOtherParameters];
_blinking = YES;
[self setMessageLabelString:NSLocalizedString(#"StartRegistration", nil)];
[self.dataManager sendRequestCommand:kConnectionTest];
}
- (void)sendRegistrationRequestConfirm:(BOOL)Confirm
{
[self setMessageLabelString:NSLocalizedString(#"StartRegistration", nil)];
NSString *registrationResult = [self.dataManager RegisterTheUSER_Confirm:Confirm];
[self processLogInResult:registrationResult];
}
- (void)processLogInResult:(NSString *)logInResult
{
if ([logInResult isEqual:#"1"]) {
if ([self.dataManager DataInitialization]) {
[self.dataManager DataInitializationForFakeUser];
[self.singlePatient SavePatient];
[self startTherapyButtonDidClicked:nil];
}
}
else if ([logInResult isEqual:#"2"]) {
if ([self.dataManager DataInitialization]) {
self.singlePatient.record7_AuthenticatedUser = YES;
[self.singlePatient SavePatient];
[self.dataManager sendRequestCommand:kNewDataAvailable];
};
}
else if ([logInResult intValue] == DEVICE_NOT_REGISTERED){
logInResult = NSLocalizedString(#"105", nil);
_blinking = NO;
[self setMessageLabelString:logInResult];
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
self.ConfirmButton.alpha = 1.0;
}];
}
else if ([logInResult isEqualToString:kNO]){
_blinking = NO;
[self setMessageLabelString:#"Cannot find the Error "];
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
}
else{
_blinking = NO;
[self setMessageLabelString:logInResult];
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
}
}
- (void)downloadZipFile
{
self.demoProgressView.progressView.progress = 1.0;
sleep(0.4);
[self setMessageLabelString:NSLocalizedString(#"Loading Data", nil)];
self.demoProgressView.progressView.progress = 0.0;
self.dataManager.blockProcessingDataPercentAge = ^(float percentAge, NSString *fileName){
if ([fileName isEqualToString:kaderenzainfo]) {
[[SingletonOperationQueue mainQueue] addOperationWithBlock:^{
self.demoProgressView.progressView.progress = percentAge;
NSLog(#"%f", percentAge);
if (percentAge == 0.5) {
sleep(0.4);
NSString *aderenzainfoFilePath = [[NSUserDefaults standardUserDefaults] objectForKey:kaccertamentiinfo];
[self.dataManager downloadZipFile:aderenzainfoFilePath fileName:kaccertamentiinfo];
}
}];
}
else if ([fileName isEqualToString:kaccertamentiinfo]){
[[SingletonOperationQueue mainQueue] addOperationWithBlock:^{
self.demoProgressView.progressView.progress = 0.5 + percentAge;
if (0.5 + percentAge >= 1.0) {
_blinking = NO;
self.CancelButton.alpha = 1.0;
if ([Patient getPatient].record_patientStatus == PatientStatusSuspendedType) {
[self setMessageLabelString:NSLocalizedString(#"SuspendedPatient", nil)];
}
else if ([Patient getPatient].record_patientStatus == PatientStatusDeletedType){
[self setMessageLabelString:NSLocalizedString(#"DeletedPatient", nil)];
}
else if ([Patient getPatient].record_patientStatus == PatientStatusActiveType){
[self setMessageLabelString:NSLocalizedString(#"SuccessfulSynchronized", nil)];
self.startTherapyButton.alpha = 1.0;
}
}
}];
}
};
NSString *aderenzainfoFilePath = [[NSUserDefaults standardUserDefaults] objectForKey:kaderenzainfo];
[self.dataManager downloadZipFile:aderenzainfoFilePath fileName:kaderenzainfo];
}
#pragma mark - DataManagerDelegate
- (void)CommunicationConnectionTest:(BOOL)connected
{
if (connected) {
[self sendRegistrationRequestConfirm:NO];
}
else{
[self setMessageLabelString:NSLocalizedString(#"connectionTestFail", nil)];
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
_blinking = NO;
}
}
- (void)CommunicationSendRequestCommandName:(NSString *)commandName
{
if ([commandName isEqualToString:kNewDataAvailable]) {
[self setMessageLabelString:NSLocalizedString(#"Synchronizing", nil)];
}
}
- (void)CommunicationReceiveResponseWithOKCommandName:(NSString *)commandName
{
}
- (void)CommunicationReceiveResponseWithRequestError:(NSString *)commandName
{
[self setMessageLabelString:NSLocalizedString(#"NetworkConnectionError", nil)];
_blinking = NO;
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
}
- (void)CommunicationReceiveResponseCommandName:(NSString *)commandName WithErrorCode:(int)errorCode withErrorDescription:(NSString *)errorDescription
{
[self setMessageLabelString:NSLocalizedString(#"NewDataAvaiableErrorCode", nil)];
_blinking = NO;
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
}
-(void)CommunicationZipFileFailDownload
{
[self setMessageLabelString:NSLocalizedString(#"ZipFileDownloadFail", nil)];
_blinking = NO;
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
}
-(void)CommunicationZipFileIsNotReadAble
{
[self setMessageLabelString:NSLocalizedString(#"ZipFileUnzippedFail", nil)];
_blinking = NO;
[UIView animateWithDuration:0.25 animations:^{
self.CancelButton.alpha = 1.0;
}];
}
#end
I solved it finally
Inside my Encryption and Decryption function, I have this:
Byte *buffer = (Byte*)malloc(asciiDataLength);
After I processed with buffer, I convert it to NSData:
NSData *plainData = [NSData dataWithBytesNoCopy:buffer length:asciiDataLength freeWhenDone:YES];
This code causes my app crushes continuously, I changed it to
NSData *plainData = [NSData dataWithBytes:buffer length:asciiDataLength];
free(buffer);
Then my app never crush again.
So, I have to free the Byte by myself, ARC will not free it for me.
Simulator's memory = Pc's RAM i.e 4 or 6 gb etc.
and device have only 1 gb maximum. In Xcode while you run the app, you need to click on Debug Navigator, and then click on Memory, it will display the memory consumption of your app.
To see the Leakage of Memory in your code - you have to go to memory tools, like Instruments.

icon grey custom UIActivityViewController

I create a custom UIActivityViewController but when I load the icons that I do makes me see gray and you are pretty much loaded correctly, someone did it happen? how you have remedied?
ActivityViewCustomActivity *ca = [[ActivityViewCustomActivity alloc]init];
ca.service = #"avanti";
ca.image = image;
ca.act = #"com.avanti.app";
ActivityViewCustomActivity *fa = [[ActivityViewCustomActivity alloc]init];
fa.service = #"facebook";
fa.image = image;//[UIImage imageNamed:#"icon-facebook.jpg"];
fa.act = #"com.facebook.app";
ActivityViewCustomActivity *tw = [[ActivityViewCustomActivity alloc]init];
tw.service = #"twitter";
tw.image = image;
tw.act = #"com.twitter.app";
UIActivityViewController *activityVC =
[[UIActivityViewController alloc] initWithActivityItems:items
applicationActivities:#[ca,fa,tw]];
activityVC.excludedActivityTypes = #[UIActivityTypePostToTwitter,UIActivityTypePostToFacebook,UIActivityTypeMail,UIActivityTypePostToWeibo, UIActivityTypeAssignToContact, UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeSaveToCameraRoll];
activityVC.completionHandler = ^(NSString *activityType, BOOL completed)
{
if ([activityType isEqualToString:#"com.avanti.app"]) {
NSLog(#" activityType: %#", activityType);
NSLog(#" completed: %i", completed);
NSString *name = [q objectAtIndex:indexPath.row];
UIStoryboard *storyboar = [UIStoryboard storyboardWithName:#"Main_iPhone" bundle:nil];
ListViewController *list = [storyboar instantiateViewControllerWithIdentifier:#"ListViewController"];
list.ide = ide;
list.canale = name;
[self.navigationController pushViewController:list animated:YES];
}
else if ([activityType isEqualToString:#"com.facebook.app"]){
NSLog(#" activityType: %#", activityType);
NSLog(#" completed: %i", completed);
UIActionSheet *action = [[UIActionSheet alloc]initWithTitle:#"Facebook" delegate:self cancelButtonTitle:#"Annulla" destructiveButtonTitle:#"Vuoi pubblicarlo ?" otherButtonTitles:#"ok", nil];
action.actionSheetStyle = UIActionSheetStyleDefault;
[self actionSheet:action clickedButtonAtIndex:2];
[action showInView:[self.view window]];
}
else if ([activityType isEqualToString:#"com.twitter.app"]){
NSLog(#" activityType: %#", activityType);
NSLog(#" completed: %i", completed);
[self shareTwitter];
}
};
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
NSLog(#"ipad");
}
else
{
[self presentViewController:activityVC animated:YES completion:nil];
}
}
e l'activity è così
- (NSString *)activityType
{
return act;
}
- (NSString *)activityTitle
{
return service;
}
- (UIImage *)activityImage
{
// CGRect rect = CGRectMake(0.0f, 0.0f, 85.0f, 85.0f);
// UIGraphicsBeginImageContext(rect.size);
//
// rect = CGRectInset(rect, 15.0f, 15.0f);
// UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:10.0f];
// [path stroke];
//
// rect = CGRectInset(rect, 0.0f, 10.0f);
// [service drawInRect:rect withFont:[UIFont fontWithName:#"Futura" size:15.0f] lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter];
//
// UIImage *imag = UIGraphicsGetImageFromCurrentImageContext();
//
// UIGraphicsEndImageContext();
// //UIImage *ima = [UIImage imageNamed:#"facebook.jpg"];
// return imag;
UIImage *ima = [UIImage imageNamed:#"Icon_Facebook.png"];
return ima;
// if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
// {
// return [UIImage imageNamed:#"Facebook_43x43"];
// }
// else
// {
// return image;
// }
}
- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems
{
NSLog(#"%s", __FUNCTION__);
for (id obj in activityItems) {
if ([obj isKindOfClass:[NSString class]]) {
return YES;
}
}
return NO;
}
- (void)prepareWithActivityItems:(NSArray *)activityItems
{
NSLog(#"%s",__FUNCTION__);
}
- (UIViewController *)activityViewController
{
NSLog(#"%s",__FUNCTION__);
return nil;
}
- (void)performActivity
{
// This is where you can do anything you want, and is the whole reason for creating a custom
// UIActivity
[self activityDidFinish:YES];
}
+ (UIActivityCategory)activityCategory
{
return UIActivityCategoryShare;
}
and the screenshot is here http://i57.tinypic.com/332vtjo.png
and .h is
#import <UIKit/UIKit.h>
#interface ActivityViewCustomActivity : UIActivity
#property (nonatomic, strong) NSString *service;
#property (nonatomic, strong) UIImage *image;
#property (nonatomic, strong) NSString *act;
- (NSString *)activityType;
- (NSString *)activityTitle;
- (UIImage *)activityImage;
- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems;
- (void)prepareWithActivityItems:(NSArray *)activityItems;
- (UIViewController *)activityViewController;
- (void)performActivity;
+ (UIActivityCategory)activityCategory;
#end
Try to add _ to your activityImage function
Something like
- (UIImage *)_activityImage
{
return [UIImage imageNamed:#"Icon_Facebook.png"];
}

Fade Effect when Scrolling

I would like to add the fade effect when user scroll my galleryViewController which fetch the data from the server. I could not able to implement the fade effect to my scrollViewController.
Code:
#import "GrillGalleryCollectionViewController.h"
#import "AFNetworking.h"
#interface GrillGalleryCollectionViewController ()
#end
#implementation GrillGalleryCollectionViewController
#synthesize scrollView,pageControl, colors;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// colors=[[NSArray alloc]init];
colors = [[NSArray alloc] init];;
[self getActiveOffers];
// NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// Update the page when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)changePage:(id)sender {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:YES];
}
- (IBAction)backBtnPressed:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
}
- (void) getActiveOffers {
NSString *string = #"http://znadesign.com/appcenter/api.php?function=get_gallery&customer_id=1";
NSLog(#"%#", string);
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
int total_count = (int)[[responseObject valueForKey:#"total_count"] integerValue];
if (total_count > 0) {
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:total_count];
for (int i = 1; i <= total_count; i++) {
NSString *key = [NSString stringWithFormat:#"%i", i];
id object = [responseObject objectForKey:key];
[array addObject:object];
}
colors = [NSArray arrayWithArray:array];
[self setSizeSliding];
// [myTableView reloadData];
}
else
{
UIAlertView *alertView2 = [[UIAlertView alloc] initWithTitle:#"There is no internet connection."
message:nil
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView2 show];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"There is no internet connection."
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}
-(void) setSizeSliding
{
for (int i = 0; i < colors.count; i++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
// UIView *subview = [[UIView alloc] initWithFrame:frame];
// subview.backgroundColor = [colors objectAtIndex:i];
// NSString *imageURLString=[[offersArray objectAtIndex:indexPath.row] valueForKey:#"picture"];
NSString*slidingImage = [[colors objectAtIndex:i] valueForKey:#"picture"];
NSURL *url = [NSURL URLWithString:slidingImage];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *tmpImage = [[UIImage alloc] initWithData:data];
UIImageView *slidingImageView = [[UIImageView alloc]initWithFrame:frame];
slidingImageView.image = tmpImage;
[self.scrollView addSubview:slidingImageView];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height);
}
#end
I want to implement the similar fade effect as it is listed below:
[UIView animateWithDuration:2
animations:^{imageView.alpha = 0.0;}
completion:^(BOOL finished){ [imageView removeFromSuperview];}];
You have the code Can you adding the below code and try whether the animation works..
-(void) animateSubViews
{
int buffer = 10;
CGRect frame = CGRectMake((self.pageControl.currentPage * self.scrollView.frame.size.width)-buffer, 0, self.scrollView.frame.size.width + buffer, self.scrollView.frame.size.height);
[UIView animateWithDuration:0.4
animations:^{
for (UIView *view in self.scrollView.subviews)
{
if (CGRectContainsRect(frame, view.frame))
{
[view setAlpha:1.0];
}
else
{
[view setAlpha:0.0];
}
}
}];
}
Try calling this method from ScrollView did scroll and change page.
- (IBAction)changePage:(id)sender {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:YES];
//Call to animate
[self animateSubViews];
}
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
// Update the page when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
//Call to animate
[self animateSubViews];
}

Trouble hiding iAd banner and displaying UIWebView in its place

When there is no iAd banner to display, we would like to display a UIWebView of the same dimensions pointed to a specific URL.
However, hiding the iAd banner and showing the UIWebView doesn't work. We embed the show/hide code inside bannerViewDidLoadAd and didFailToReceiveAdWithError. All that appears is the white, blank rectangle when there is no iAd inventory instead of our UIWebView.
If a user clicks on a link inside the UIWebView, we would like the link to open in Safari. Do we need to add a delegate to the UIWebView?
Code:
//
// SAiOSAdPlugin.m
// Ad Plugin for PhoneGap
//
// Created by shazron on 10-07-12.
// Copyright 2010 Shazron Abdullah. All rights reserved.
// Cordova v1.5.0 Support added 2012 #RandyMcMillan
//
#import "SAiOSAdPlugin.h"
//#ifdef CORDOVA_FRAMEWORK
#import <Cordova/CDVDebug.h>
//#else
//#import "CDVDebug.h"
//#endif
#interface SAiOSAdPlugin(PrivateMethods)
- (void) __prepare:(BOOL)atBottom;
- (void) __showAd:(BOOL)show;
#end
#implementation SAiOSAdPlugin
#synthesize adView;
#synthesize bannerIsVisible, bannerIsInitialized, bannerIsAtBottom, isLandscape;
#pragma mark -
#pragma mark Public Methods
- (void) resizeViews
{
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass && self.adView)
{
CGRect webViewFrame = [super webView].frame;
CGRect superViewFrame = [[super webView] superview].frame;
CGRect adViewFrame = self.adView.frame;
BOOL adIsShowing = [[[super webView] superview].subviews containsObject:self.adView];
if (adIsShowing)
{
if (self.bannerIsAtBottom) {
webViewFrame.origin.y = 0;
CGRect adViewFrame = self.adView.frame;
CGRect superViewFrame = [[super webView] superview].frame;
adViewFrame.origin.y = (self.isLandscape ? superViewFrame.size.width : superViewFrame.size.height) - adViewFrame.size.height;
self.adView.frame = adViewFrame;
} else {
webViewFrame.origin.y = adViewFrame.size.height;
}
webViewFrame.size.height = self.isLandscape? (superViewFrame.size.width - adViewFrame.size.height) : (superViewFrame.size.height - adViewFrame.size.height);
}
else
{
webViewFrame.size = self.isLandscape? CGSizeMake(superViewFrame.size.height, superViewFrame.size.width) : superViewFrame.size;
webViewFrame.origin = CGPointZero;
}
[UIView beginAnimations:#"blah" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[super webView].frame = webViewFrame;
[UIView commitAnimations];
}
}
- (void) orientationChanged:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
{
NSInteger orientation = [[arguments objectAtIndex:0] integerValue];
switch (orientation) {
// landscape
case 90:
case -90:
self.isLandscape = YES;
break;
// portrait
case 0:
case 180:
self.isLandscape = NO;
break;
default:
break;
}
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass && self.adView)
{
self.adView.currentContentSizeIdentifier = self.isLandscape ? ADBannerContentSizeIdentifierLandscape : ADBannerContentSizeIdentifierPortrait;
[self resizeViews];
}
}
- (void) prepare:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
NSUInteger argc = [arguments count];
if (argc > 1) {
return;
}
NSString* atBottomValue = [arguments objectAtIndex:0];
[self __prepare:[atBottomValue boolValue]];
}
- (void) showAd:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
NSUInteger argc = [arguments count];
if (argc > 1) {
return;
}
NSString* showValue = [arguments objectAtIndex:0];
[self __showAd:[showValue boolValue]];
}
#pragma mark -
#pragma mark Private Methods
- (void) __prepare:(BOOL)atBottom
{
NSLog(#"SAiOSAdPlugin Prepare Ad At Bottom: %d", atBottom);
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass && !self.adView)
{
self.adView = [[ADBannerView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
// we are still using these constants even though they are deprecated - if it is changed, iOS 4 devices < 4.3 will crash.
// will need to do a run-time iOS version check
self.adView.requiredContentSizeIdentifiers = [NSSet setWithObjects: ADBannerContentSizeIdentifierPortrait, ADBannerContentSizeIdentifierLandscape, nil];
self.adView.delegate = self;
NSString* contentSizeId = (self.isLandscape ? ADBannerContentSizeIdentifierLandscape : ADBannerContentSizeIdentifierPortrait);
self.adView.currentContentSizeIdentifier = contentSizeId;
if (atBottom) {
self.bannerIsAtBottom = YES;
}
self.bannerIsVisible = NO;
self.bannerIsInitialized = YES;
self.houseAdView = [[UIWebView alloc] initWithFrame: CGRectMake(0.0, 0.0, 1.0, 1.0)];
self.houseAdView.frame = self.adView.frame;
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://www.panabee.com"]];
[self.houseAdView loadRequest: request];
}
}
- (void) __showAd:(BOOL)show
{
NSLog(#"SAiOSAdPlugin Show Ad: %d", show);
if (!self.bannerIsInitialized){
[self __prepare:NO];
}
if (!(NSClassFromString(#"ADBannerView") && self.adView)) { // ad classes not available
return;
}
if (show == self.bannerIsVisible) { // same state, nothing to do
return;
}
if (show)
{
[UIView beginAnimations:#"blah" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[[[super webView] superview] addSubview:self.adView];
[[[super webView] superview] bringSubviewToFront:self.houseAdView];
[[[super webView] superview] bringSubviewToFront:self.adView];
[self resizeViews];
[UIView commitAnimations];
self.bannerIsVisible = YES;
}
else
{
[UIView beginAnimations:#"blah" context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[self.adView removeFromSuperview];
[self resizeViews];
[UIView commitAnimations];
self.bannerIsVisible = NO;
}
}
#pragma mark -
#pragma ADBannerViewDelegate
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass)
{
NSString* jsString =
#"(function(){"
"var e = document.createEvent('Events');"
"e.initEvent('iAdBannerViewDidLoadAdEvent');"
"document.dispatchEvent(e);"
"})();";
[banner setHidden:YES];
[self.houseAdView setHidden:NO];
[super writeJavascript:[NSString stringWithFormat:jsString]];
}
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError*)error
{
Class adBannerViewClass = NSClassFromString(#"ADBannerView");
if (adBannerViewClass)
{
NSString* jsString =
#"(function(){"
"var e = document.createEvent('Events');"
"e.initEvent('iAdBannerViewDidFailToReceiveAdWithErrorEvent');"
"e.error = '%#';"
"document.dispatchEvent(e);"
"})();";
[banner setHidden:YES];
[self.houseAdView setHidden:NO];
[super writeJavascript:[NSString stringWithFormat:jsString, [error description]]];
}
}
#end
It's me again :)
You're not adding it to the sub view tree.
From your __prepare method
self.houseAdView = [[UIWebView alloc] initWithFrame: CGRectMake(0.0, 0.0, 1.0, 1.0)];
self.houseAdView.frame = self.adView.frame;
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://www.panabee.com"]];
[self.houseAdView loadRequest: request];
That's great. But it doesn't work - you are missing one line of code - a critical, vital line that gets every developer some time or another.
[self addSubview:self.houseAdView];
I'm making a few assumptions, like that self is a UIView. Test before shipping.
So, that part of your __prepare method should look like this:
self.houseAdView = [[UIWebView alloc] initWithFrame: CGRectMake(0.0, 0.0, 1.0, 1.0)];
self.houseAdView.frame = self.adView.frame;
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://www.panabee.com"]];
[self.houseAdView loadRequest: request];
[self addSubview:self.houseAdView];

CATiledLayer and not rendered slices

The problem:
I've to render a big image 7148x15000px (a custom map), so i've looking around for something usefull and i've found BitmapSlice, but the problem is that the very first time i run the app (on device and simulator) several slices aren't loaded correctly and i see the image with large black holes.
Code:
BitmapSliceViewController.h
#import <UIKit/UIKit.h>
#interface BitmapSliceViewController : UIViewController<UIScrollViewDelegate>
#property (nonatomic, retain) UIImageView *_zoomView;
#property (nonatomic, retain) IBOutlet UIScrollView *scrollView;
- (void)saveTilesOfSize:(CGSize)size forImage:(UIImage*)image toDirectory
(NSString*)directoryPath usingPrefix:(NSString*)prefix;
#end
BitmapSliceViewController.m
#import "BitmapSliceViewController.h"
#import "TileView.h"
#implementation BitmapSliceViewController
#synthesize scrollView;
- (void)dealloc
{
[super dealloc];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *directoryPath = [paths objectAtIndex:0];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *big = [UIImage imageNamed:#"map.jpg"];
[self saveTilesOfSize:(CGSize){256, 256} forImage:big toDirectory:directoryPath usingPrefix:#"map_"];
dispatch_async(dispatch_get_main_queue(), ^{
[scrollView setNeedsDisplay];
});
});
TileView *tv = [[TileView alloc] initWithFrame:(CGRect){{0,0}, (CGSize){7148,15000}}];
[tv setTileTag:#"map_"];
[tv setTileDirectory:directoryPath];
[scrollView addSubview:tv];
[scrollView setContentSize:(CGSize){7148,15000}];
[scrollView setDelegate:self];
}
- (void)saveTilesOfSize:(CGSize)size
forImage:(UIImage*)image
toDirectory:(NSString*)directoryPath
usingPrefix:(NSString*)prefix
{
CGFloat cols = [image size].width / size.width;
CGFloat rows = [image size].height / size.height;
int fullColumns = floorf(cols);
int fullRows = floorf(rows);
CGFloat remainderWidth = [image size].width - (fullColumns * size.width);
CGFloat remainderHeight = [image size].height - (fullRows * size.height);
if (cols > fullColumns) fullColumns++;
if (rows > fullRows) fullRows++;
CGImageRef fullImage = [image CGImage];
for (int y = 0; y < fullRows; ++y) {
for (int x = 0; x < fullColumns; ++x) {
CGSize tileSize = size;
if (x + 1 == fullColumns && remainderWidth > 0) {
// Last column
tileSize.width = remainderWidth;
}
if (y + 1 == fullRows && remainderHeight > 0) {
// Last row
tileSize.height = remainderHeight;
}
CGImageRef tileImage = CGImageCreateWithImageInRect(fullImage,
(CGRect){{x*size.width, y*size.height},
tileSize});
NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:tileImage], 1);
CGImageRelease(tileImage);
NSString *path = [NSString stringWithFormat:#"%#/%#%d_%d.png",
directoryPath, prefix, x, y];
[imageData writeToFile:path atomically:NO];
}
}
}
#end
TileView.h
#interface TileView : UIView
#property (nonatomic, copy) NSString *tileTag;
#property (nonatomic, copy) NSString *tileDirectory;
- (UIImage*)tileAtCol:(int)col row:(int)row;
#end
TileView.m
#import "TileView.h"
#implementation TileView
#synthesize tileTag;
#synthesize tileDirectory;
+ layerClass
{
return [CATiledLayer class];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (!self) return nil;
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)drawRect:(CGRect)rect {
//CGContextRef context = UIGraphicsGetCurrentContext();
CGSize tileSize = (CGSize){256, 256};
int firstCol = floorf(CGRectGetMinX(rect) / tileSize.width);
int lastCol = floorf((CGRectGetMaxX(rect)-1) / tileSize.width);
int firstRow = floorf(CGRectGetMinY(rect) / tileSize.height);
int lastRow = floorf((CGRectGetMaxY(rect)-1) / tileSize.height);
for (int row = firstRow; row <= lastRow; row++) {
for (int col = firstCol; col <= lastCol; col++) {
UIImage *tile = [self tileAtCol:col row:row];
if (tile)
{
CGRect tileRect = CGRectMake(tileSize.width * col, tileSize.height * row, tileSize.width, tileSize.height);
tileRect = CGRectIntersection(self.bounds, tileRect);
[tile drawInRect:tileRect];
// [[UIColor whiteColor] set];
// CGContextSetLineWidth(context, 6.0);
// CGContextStrokeRect(context, tileRect);
}
}
}
}
- (UIImage*)tileAtCol:(int)col row:(int)row
{
NSString *path = [NSString stringWithFormat:#"%#/%#%d_%d.png", tileDirectory, tileTag, col, row];
return [UIImage imageWithContentsOfFile:path];
}
#end
This is the main code of the app, you can download the entire example from the site linked on the top of the post.
As i said the main problem is the rendering of some slices that fail in the first run of the app, other runs seem works correctly.
modifing a bit - (UIImage*)tileAtCol:(int)col row:(int)row
- (UIImage*)tileAtCol:(int)col row:(int)row
{
NSString *path = [NSString stringWithFormat:#"%#/%#%d_%d.png", tileDirectory, tileTag, col, row];
UIImage *img = [UIImage imageWithContentsOfFile:path];
if (img) {
NSLog(#"good");
}
else {
NSLog(#"bad");
}
return img;
}
The problem seems to be here...
Any ideas to fix it?
Thanks in advance

Resources