您的位置:首页 > 移动开发 > Swift

监测iOS截屏(Swift)

2015-11-17 20:55 387 查看
//

// ScreenshotManager.swift

// ImagePicker

//

// Created by 成杰 on 15/11/17.

// Copyright © 2015年
成杰. All rights reserved.

//

import UIKit

import Foundation

import AssetsLibrary

class ScreenshotManager:
NSObject {



private var completion: ((UIImage) ->
Void)? = nil

class func detectScreenshot(completion: ((UIImage) ->
Void)?) {

let shared =
self.shared

shared.completion = completion

shared.startTimer()

}



private static
var shared: ScreenshotManager {

dispatch_once(&Inner.token) { () ->
Void in

Inner.instance =
ScreenshotManager()

}

return Inner.instance!

}



private struct Inner {

static var instance:
ScreenshotManager?

static var token:
dispatch_once_t =
0

}



private var timer:
NSTimer? = nil

private func startTimer() {

timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target:
self, selector: "checkNewScreenshot", userInfo:
nil, repeats: true)

}



private func stopTimer() {

if timer !=
nil {

timer!.invalidate()

timer =
nil

}

}



private var groupCountDic = [String:
Int]()

func checkNewScreenshot() {

print("ing...")

let library =
ALAssetsLibrary()

library.enumerateGroupsWithTypes(ALAssetsGroupSavedPhotos, usingBlock: { (group, stop) ->
Void in

if group !=
nil {

guard
let groupName = group.valueForProperty(ALAssetsGroupPropertyPersistentID)
as?
String else {

return

}

group.setAssetsFilter(ALAssetsFilter.allPhotos())

if
self.groupCountDic[groupName] ==
nil {

self.groupCountDic[groupName] = group.numberOfAssets()

}

if group.numberOfAssets() >
self.groupCountDic[groupName]! {

group.enumerateAssetsAtIndexes(NSIndexSet(index: group.numberOfAssets()-1), options: .Concurrent,
usingBlock: { (alAsset, index, innerStop) -> Void
in

if alAsset !=
nil {

let representation = alAsset.defaultRepresentation()

let latestPhoto =
UIImage(CGImage: representation.fullScreenImage().takeUnretainedValue())

if latestPhoto.isScreenshot() {

dispatch_async(dispatch_get_main_queue(), { () ->
Void in

if
self.completion !=
nil {

self.completion!(latestPhoto)

}

})

}

self.groupCountDic[groupName] = group.numberOfAssets()

}

})

}

}

}) { (error) -> Void
in

print("error:\(error)")

}

}



class func stopDetectingScreenshots() {

self.shared.stopTimer()

self.shared.completion =
nil

self.shared.timer =
nil

}

}

extension UIImage {

func isScreenshot() ->
Bool {

let imageWidth =
self.size.width;

let imageHeight =
self.size.height;

let screenWidth =
UIScreen.mainScreen().bounds.size.width

let screenHeight =
UIScreen.mainScreen().bounds.size.height

return (fmod(imageWidth, screenWidth) ==
0 && fmod(imageHeight, screenHeight) ==
0) || (fmod(imageWidth, screenHeight) ==
0 && fmod(imageHeight, screenWidth) ==
0)

}

}

// 用法

ScreenshotManager.detectScreenshot { (image) -> Void
in

self.imageView.image = image

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: