应用启动后加载广告(swift)
2017-02-28 本文已影响366人
MangoJ
第三讲开始了!
如果问我,我每天接触什么信息最多,那就非广告莫属了,劈天盖地的广告随处可见,我们讨厌这些广告的同时,别忘了广告也会对我们有一定的帮助,广告可以引导我们去做一些我们需要但不了解的事物,也许这个广告对你没有帮助,但对他有帮助,所以才会有广告这个行业.当然这不是今天的重点😆!言归正传进入我们开发中!
在我们使用过的APP中有80%的APP都会有广告的出现,这也就体现了广告模块开发的重要性!
广告的加载可以分很多种场景,例如:1.有的会在启动图过后立即加载广告,2.有的会在应用加载完成几秒后加载广告,3.还有的是在你完成某个动作后加载广告等等,广告加载的样式也各有千秋,我今天要讲的就是第一种在启动图过后立刻加载广告,这是应用比较广的一种.
下面👇我们就研究一下作为开发人员如何设计广告页面,首先我们先确定一下思路.
1.既然要加载广告首先我们需要创建广告视图
import UIKit
let kScreenWidth = UIScreen.main.bounds.width
let kScreenHight = UIScreen.main.bounds.height
class AdvertView: UIView {
var advView = UIImageView()
var skipButton = UIButton()
var imageFilePath : String?
var timer :Timer!
var time:Int = 3
override init(frame:CGRect) {
super.init(frame: frame)
//设置广告图片
advView = UIImageView.init(frame: frame)
advView.isUserInteractionEnabled = true
advView.contentMode = UIViewContentMode.scaleAspectFill
advView.clipsToBounds = true
advView.backgroundColor = UIColor.red
if (imageFilePath != nil) {
advView.image = UIImage(contentsOfFile: imageFilePath!)
}
//给广告图片添加手势
let imageTap = UITapGestureRecognizer(target: self, action: #selector(pushAdDetail))
advView.addGestureRecognizer(imageTap)
//跳过按钮
let btnW:CGFloat = 60
let btnH:CGFloat = 30
skipButton = UIButton(frame: CGRect(x: kScreenWidth - btnW, y: btnH, width: btnW, height: btnH))
skipButton.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
skipButton.setTitle("跳过\(time)", for: .normal)
skipButton.setTitleColor(UIColor.white, for: .normal)
skipButton.backgroundColor = UIColor.gray
skipButton.layer.cornerRadius = 4
self.addSubview(advView)
self.addSubview(skipButton)
// 启用计时器,控制每秒执行一次tickDown方法
timer = Timer.scheduledTimer(timeInterval: TimeInterval(1), target: self, selector: #selector(tickDown), userInfo: nil, repeats: true)
}
//定时器触发的方法
func tickDown() {
self.time -= 1
skipButton.setTitle("跳过\(time)", for: .normal)
//如果剩余时间小于等于0
if(self.time <= 0){
//取消定时器
self.timer.invalidate()
dismiss()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func tapAction() {
dismiss()
}
//移除广告
func dismiss() {
self.timer.invalidate()
self.timer = nil
UIView.animate(withDuration: 0.3, animations: {
self.alpha = 0
}) { (finish) in
self.removeFromSuperview()
}
}
//发送通知
func pushAdDetail() {
dismiss()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "pushAd"), object: nil)
}
//显示广告视图
func show() {
let window = UIApplication.shared.keyWindow
window?.addSubview(self)
}
}
2.既然我们要将广告显示在加载完启动图后,那么我们加载广告的代码就要在AppDelegate内被触发.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool{}
3.加载广告是每次程序运行时都需要加载的,考虑到用户体验,广告加载时间会很短,所以要考虑如果网络缓慢也不要有延迟,那么需将图片异步下载到本地,并保存图片名,每次打开APP时先根据本地存储的图片名查找沙盒中是否存在该图片,如果存在,则显示广告页。
因为是异步下载缓存广告图片所以要判断当前存在的广告图片是否是最新的广告图,如果是则只显示不重复缓存,如果不是最新广告图需显示当前图片然后删除当前图片缓存最新图片在下次进入APP时展示!
import UIKit
let adImageName = "adImageName"
let adUrl = "adUrl"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var advertView = AdvertView()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
let nav = UINavigationController(rootViewController: ViewController())
self.window?.rootViewController = nav
self.window?.makeKeyAndVisible()
// 1.判断沙盒中是否存在广告图片,如果存在,直接显示
let image = UserDefaults.standard.value(forKey: adImageName) as! String? ?? " "
let filePath = NSHomeDirectory().appending("/Documents/\(image)")
let isExist = self.isFileExist(withFilePath: (filePath))
if isExist {
advertView = AdvertView.init(frame: CGRect(x: 0, y: 0, width: (self.window?.bounds.size.width)!, height: (self.window?.bounds.size.height)!))
advertView.advView.image = UIImage(contentsOfFile: filePath)
advertView.backgroundColor = UIColor.red
advertView.show()
}
// 2.无论沙盒中是否存在广告图片,都需要重新调用广告接口,判断广告是否更新
self.getAdvertisingImage()
return true
}
/**
* 初始化广告页面
*/
func getAdvertisingImage() {
// TODO 请求广告接口
// 这里原本采用美团的广告接口,现在了一些固定的图片url代替
var imageArray: [Any] = [ "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1488259299&di=5fd14456fb2a6fb5b0a6a3e7ec8286d0&src=http://a-ssl.duitang.com/uploads/item/201510/30/20151030103110_zNCht.jpeg"]
//https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488269385582&di=44087eed1458b25e9cb8958ea7960198&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fmobile%2Fb%2F5591f15baf5a7.jpg
let imageUrl: String = imageArray[0] as! String
// 获取图片名:43-130P5122Z60-50.jpg
let stringArr: [Any] = imageUrl.components(separatedBy: "/")
let imageName: String = (stringArr.last as! String?)!
// 拼接沙盒路径
let filePath: String = NSHomeDirectory().appending("/Documents/\(imageName)")
let isExist: Bool = self.isFileExist(withFilePath: filePath)
if !isExist {
// 如果该图片不存在,则删除老图片,下载新图片
self.downloadAdImage(withUrl: imageUrl, imageName: imageName)
}
}
/**
* 判断文件是否存在
*/
func isFileExist(withFilePath filePath: String) -> Bool {
let fileManager = FileManager.default
var isDirectory:ObjCBool = false
return fileManager.fileExists(atPath: filePath, isDirectory : &isDirectory)
}
/**
* 下载新图片
*/
func downloadAdImage(withUrl imageUrl: String, imageName: String) {
DispatchQueue.global(qos: .default).async(execute: {() -> Void in
let url = URL(string: imageUrl)
let data :Data? = try? Data(contentsOf: url!)
let filePath: String = NSHomeDirectory().appending("/Documents/\(imageName)")
let fileManager = FileManager.default
fileManager.createFile(atPath: filePath, contents: data , attributes: nil)
self.deletOldImage()
UserDefaults.standard.set(imageName, forKey: adImageName)
UserDefaults.standard.synchronize()
})
}
/**
* 删除旧图片
*/
func deletOldImage() {
let imageName = UserDefaults.standard.value(forKey: adImageName)!
if (imageName != nil) {
let filePath = NSHomeDirectory().appending("/Documents/\(imageName)")
let fileManager:FileManager = FileManager.default
try? fileManager.removeItem(atPath: filePath)
}
}
}
4.点击广告视图时进入广告详情页面,需要注意的是要从首页push进入广告详情页.
在AdvertView的pushAdDetail()方法中发送通知,在ViewController中viewDidLoad方法接受通知并执行跳转pushAd()方法!
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(pushAd), name: NSNotification.Name(rawValue: "pushAd"), object: nil)
self.view.backgroundColor = UIColor.white
}
func pushAd() {
let advertVc = AdvertDetailViewController()
self.navigationController?.pushViewController(advertVc, animated: true)
}
}
广告的加载大功告成,相信本讲,对读者朋友会有所帮助,如果觉得文章还可以,点击下方👇喜欢鼓励一下,没关注的朋友可以点击一下关注,专题系列讲解持续更新中!
专题目录:Swift开发之功能模块