ios entry advertising

Keywords: iOS Android github Swift

This article introduces a function that almost every APP needs to use. The APP starts the entry advertisement. I originally wanted to make ios android into Demo and put it on github. Considering the time relationship, it's OK. But I want to make sure that the code here can be run after copying and pasting, because I am also the God of copying and pasting.
First, ios is introduced, and then android and server code are pasted out.
The logic of demand is as follows: advertising is not immutable. It needs to change pictures at any time, time of getting on and off the shelves, display when starting, save locally first, and click to jump. Let's talk about it with the code

The data format returned by the server and the interface request are placed in the didFinishLaunchingWithOptions method of AppDelegate

adver =     (
                {
            endtime = 1516622424;
            id = 7;
            link = "https://www.baidu.com";
            pic = "/uploads/image/18/01/5a65608db3ebb.png";
        }
    );

Get the data and save it locally:

// Entry advertisement
        NSMutableArray *ad_pics_array = [result.data objectForKey:@"adver"];
        if (ad_pics_array && ad_pics_array.count > 0) {
            NSDate *endTime = [NSDate dateWithTimeIntervalSince1970:[[[ad_pics_array objectAtIndex:0] objectForKey:@"endtime"] doubleValue]];
            // Effective time of entering advertisement
            [[NSUserDefaults standardUserDefaults] setObject:endTime forKey:AD_PICS_ENDTIME];
            if (ad_pics_array && ad_pics_array.count > 0) {
                dispatch_once(&picDownloadToken, ^{
                    [self performSelectorInBackground:@selector(picDownloadData:) withObject:ad_pics_array];
                });
            }
            [[NSUserDefaults standardUserDefaults] setObject:GETTEXT([ad_pics_array objectAtIndex:0], @"link") forKey:AD_PICS_CONNECT];
        } else {
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:AD_PICS_ENDTIME];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:AD_PICS_CONNECT];
        }
- (void)picDownloadData:(NSArray*)ad_pics_array {
    NSString *picUrl = [[ad_pics_array objectAtIndex:0] objectForKey:@"pic"];
    
    NSString *picUrl_local = [[NSUserDefaults standardUserDefaults] objectForKey:AD_PICS_ADDRESS];

    if (![picUrl isEqualToString:picUrl_local]) {
        NSLog(@"Perform picture download");
        NSString *urlString = [Constant getImgHttpAdress:[[ad_pics_array objectAtIndex:0] objectForKey:@"pic"]];
        NSLog(@"====>%@",urlString);
        NSData * picData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[urlString remoteImageAspectFill:SCREEN_WIDTH * [UIScreen mainScreen].scale height:SCREEN_HEIGHT * [UIScreen mainScreen].scale noScale:NO]]];
        if (picData) {
            UIImage * imageFromURL = [UIImage imageWithData:picData];
            
            NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            
            NSLog(@"Save path:%@",documentsDirectoryPath);
            
            [UIImageJPEGRepresentation(imageFromURL, 0.8) writeToFile:[documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", @"adPic", @"jpg"]] options:NSAtomicWrite error:nil];
            
            // Address for entering advertisement
            [[NSUserDefaults standardUserDefaults] setObject:picUrl forKey:AD_PICS_ADDRESS];
        }
    }
}

It is recommended to load the entry ads in the didFinishLaunchingWithOptions method of AppDelegate, or in the first viewCtroller:

- (void)ad_pic_show {
    NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //String splicing to get the complete path of the file
    NSString *ad_pic_name = @"/adPic.jpg";
    NSString *ad_pic_path = [documentsDirectoryPath stringByAppendingString:ad_pic_name];
    NSLog(@"The full path is:%@",ad_pic_path);
    
    NSData *ad_pic_data = [NSData dataWithContentsOfFile:ad_pic_path];
    if (ad_pic_data){
        UIImage *ad_pic_image = [UIImage imageWithData:ad_pic_data];
        NSDate *endTime = [[NSUserDefaults standardUserDefaults] objectForKey:AD_PICS_ENDTIME];
        NSDate *nowTime = [NSDate date];
        
        if ([endTime isEqualToDate:[endTime laterDate:nowTime]] && ad_pic_image){
            [ADLaunchView showAdView:ad_pic_image];
        }
    }
}

ADLaunchView.h and ADLaunchView.m:

#import <UIKit/UIKit.h>

@interface ADLaunchView : UIView

@property (nonatomic, strong) UIImage *adImage;

+ (void)showAdView:(UIImage *)adImage;

@end

#import "ADLaunchView.h"
#import "LoginHomeViewController.h"
#import "Community-Swift.h"

@implementation ADLaunchView {
    NSTimer *m_pTimer;
    int inputSeconds;
    UILabel *secLabel;
    UIButton *contentBtn;
    UIImageView *adimg;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        adimg = [[UIImageView alloc]initWithFrame:frame];
        adimg.backgroundColor = [UIColor orangeColor];
        [self addSubview:adimg];
        adimg.userInteractionEnabled = YES;
        contentBtn = [[UIButton alloc] initWithFrame:adimg.bounds];
        contentBtn.backgroundColor = [UIColor clearColor];
        [contentBtn addTarget:self action:@selector(contentBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [adimg addSubview:contentBtn];
        
        UIView * timeBg = [[UIView alloc]initWithFrame:CGRectMake(frame.size.width-80, 30, 65, 30)];
        timeBg.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.5];
        timeBg.layer.cornerRadius = 15;
        timeBg.clipsToBounds = YES;
        timeBg.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.3];
        [adimg addSubview:timeBg];
        timeBg.userInteractionEnabled = YES;
        UITapGestureRecognizer *popTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeAction)];
        [timeBg addGestureRecognizer:popTap];
        
        UILabel * woldLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 32, 20)];
        woldLabel.text = @"skip";
        woldLabel.textColor = [UIColor whiteColor];
        woldLabel.textAlignment = 1;
        woldLabel.font  = [UIFont systemFontOfSize:15.0];
        [timeBg addSubview:woldLabel];
        
        
        secLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(woldLabel.frame), 5, 20, 20)];
        secLabel.textColor = [Constant colorOfDefined:@"#ff9900"];
        secLabel.font = [UIFont systemFontOfSize:15.0];
        secLabel.textAlignment = 1;
        [timeBg addSubview: secLabel];
        inputSeconds = 3;
        secLabel.text = [NSString stringWithFormat:@"%d",inputSeconds];
        m_pTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                     target:self selector:@selector(calcuRemainTime)
                                                   userInfo:nil repeats:YES];
    }
    return self;
}

- (void)setAdImage:(UIImage *)adImage {
    adimg.image = adImage;
}

/*
 *Countdown remaining time calculation
 */
- (void)calcuRemainTime
{
    inputSeconds--;
    if (inputSeconds >= 0) {
        secLabel.text = [NSString stringWithFormat:@"%d",inputSeconds];
    }
    if (inputSeconds <= 0.0) {
        [m_pTimer invalidate];
        m_pTimer = nil;
        
        [self closeAction];
    }
}

- (void)closeAction {
    self.userInteractionEnabled = NO;
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    
    // Animation options settings
    animation.duration = 1.5; // Animation duration
    animation.repeatCount = 0; // Number of repetitions
    animation.autoreverses = NO; // Reverse animation at the end of the animation
    animation.delegate = self;
    
    // Zoom factor
    animation.fromValue = [NSNumber numberWithFloat:1.0]; // Multiplier at start
    animation.toValue = [NSNumber numberWithFloat:1.5]; // Multiplier at end
    // Add animation
    [self.layer addAnimation:animation forKey:@"scale-layer"];
    [UIView animateWithDuration:0.6 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
//        [self removeFromSuperview];
    }];
}

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
    if (flag) {
        [self removeFromSuperview];
    }
}

- (void)contentBtnAction {
    NSString *link = [[NSUserDefaults standardUserDefaults] objectForKey:AD_PICS_CONNECT];
    if (link) {
        SQ_OPEN(link, @"");
        [self closeAction];
        for (UIViewController *vc in [AppDelegate sharedAppDelegate].topNavigationController.viewControllers) {
            if ([vc isKindOfClass:[LoginHomeViewController class]]) {
                [vc removeFromParentViewController];
                [[AppDelegate sharedAppDelegate].topNavigationController setNavigationBarHidden:NO animated:YES];
                break;
            }
        }
    }
}

+ (void)showAdView:(UIImage *)adImage1 {
    ADLaunchView *adView = [[ADLaunchView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    adView.adImage = adImage1;
    [[AppDelegate sharedAppDelegate].window addSubview:adView];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

There will be a small problem here, that is, changing the advertising image or opening the app for the first time will not display the advertising ~ ~ because I want to save the image for the first time, which is very understandable.

Posted by Zetusko on Fri, 01 May 2020 04:11:30 -0700