Skip to content
This repository has been archived by the owner on Jan 18, 2025. It is now read-only.

Commit

Permalink
Remove extraneous lines
Browse files Browse the repository at this point in the history
  • Loading branch information
LeonardoCardoso committed Sep 23, 2018
1 parent f8d2bc8 commit c8ae80d
Show file tree
Hide file tree
Showing 20 changed files with 345 additions and 356 deletions.
16 changes: 8 additions & 8 deletions Example/SwiftLinkPreviewExample/AlamofireSource.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ import AlamofireImage
import ImageSlideshow

public class AlamofireSource: NSObject, InputSource {

var url: NSURL?

public init(url: NSURL) {
self.url = url
super.init()
}

public init?(urlString: String) {
if let validUrl = NSURL(string: urlString) {
self.url = validUrl
Expand All @@ -28,20 +28,20 @@ public class AlamofireSource: NSObject, InputSource {
return nil
}
}

public func load(to imageView: UIImageView, with callback: @escaping (UIImage?) -> Void) {

guard let url = self.url as URL? else { return }
imageView.af_setImage(withURL: url,
placeholderImage: nil,
filter: nil,
progress: nil) { (response) in

imageView.image = response.result.value

if let value = response.result.value { callback(value) }

}
}

}
19 changes: 8 additions & 11 deletions Example/SwiftLinkPreviewExample/Delegates/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,37 +10,34 @@ import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?



func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}

func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


}

}
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ import PackageDescription

let package = Package(
name: "SwiftLinkPreview"
)
)
33 changes: 16 additions & 17 deletions Sources/Cache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,44 +9,43 @@
import Foundation

public protocol Cache {

func slp_getCachedResponse(url: String) -> SwiftLinkPreview.Response?

func slp_setCachedResponse(url: String, response: SwiftLinkPreview.Response?)
}

public class DisabledCache: Cache {

public static let instance = DisabledCache()

public func slp_getCachedResponse(url: String) -> SwiftLinkPreview.Response? { return nil; }

public func slp_setCachedResponse(url: String, response: SwiftLinkPreview.Response?) { }
}


open class InMemoryCache: Cache {
private var cache = Dictionary<String, (response: SwiftLinkPreview.Response, date: Date)>()
private let invalidationTimeout: TimeInterval
private let cleanupTimer: DispatchSource?

//High priority queue for quick responses
private static let cacheQueue = DispatchQueue(label: "SwiftLinkPreviewInMemoryCacheQueue", qos: .userInitiated, target: DispatchQueue.global(qos: .userInitiated))

public init(invalidationTimeout: TimeInterval = 300.0, cleanupInterval: TimeInterval = 10.0) {
self.invalidationTimeout = invalidationTimeout
self.cleanupTimer = DispatchSource.makeTimerSource(queue: type(of:self).cacheQueue) as? DispatchSource

self.cleanupTimer = DispatchSource.makeTimerSource(queue: type(of: self).cacheQueue) as? DispatchSource
self.cleanupTimer?.schedule(deadline: .now() + cleanupInterval, repeating: cleanupInterval)

self.cleanupTimer?.setEventHandler { [weak self] in
guard let sself = self else {return}
sself.cleanup()
}

self.cleanupTimer?.resume()
}

open func cleanup() {
type(of: self).cacheQueue.async {
for (url, data) in self.cache {
Expand All @@ -56,19 +55,19 @@ open class InMemoryCache: Cache {
}
}
}

open func slp_getCachedResponse(url: String) -> SwiftLinkPreview.Response? {
return type(of: self).cacheQueue.sync {
guard let response = cache[url] else { return nil }

if response.date.timeIntervalSinceNow >= invalidationTimeout {
slp_setCachedResponse(url: url, response: nil)
return nil
}
return response.response
}
}

open func slp_setCachedResponse(url: String, response: SwiftLinkPreview.Response?) {
type(of: self).cacheQueue.sync {
if let response = response {
Expand All @@ -78,7 +77,7 @@ open class InMemoryCache: Cache {
}
}
}

deinit {
self.cleanupTimer?.cancel()
}
Expand Down
12 changes: 6 additions & 6 deletions Sources/NSURLSessionExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,21 @@
import Foundation

public extension URLSession {

public func synchronousDataTask(with url: URL) -> (Data?, URLResponse?, NSError?) {

var data: Data?, response: URLResponse?, error: NSError?
let semaphore = DispatchSemaphore(value: 0)

dataTask(with: url, completionHandler: {

data = $0; response = $1; error = $2 as NSError?
semaphore.signal()

}) .resume()

_ = semaphore.wait(timeout: DispatchTime.distantFuture)

return (data, response, error)

}
Expand Down
70 changes: 35 additions & 35 deletions Sources/Regex.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Foundation

// MARK: - Regular expressions
class Regex {

static let imagePattern = "(.+?)\\.(gif|jpg|jpeg|png|bmp)$"
static let imageTagPattern = "<img(.+?)src=\"([^\"](.+?))\"(.+?)[/]?>"
static let titlePattern = "<title(.*?)>(.*?)</title>"
Expand All @@ -23,45 +23,45 @@ class Regex {
static let scriptPattern = "<script(.*?)>"
static let commentPattern = "<!--(.*?)-->"
static let hrefPattern = ".*href=\"(.*?)\".*"

// Test regular expression
static func test(_ string: String, regex: String) -> Bool {

return Regex.pregMatchFirst(string, regex: regex) != nil

}

// Match first occurrency
static func pregMatchFirst(_ string: String, regex: String, index: Int = 0) -> String? {
do{

do {

let rx = try NSRegularExpression(pattern: regex, options: [.caseInsensitive])
if let match = rx.firstMatch(in: string, options: [], range: NSMakeRange(0, string.count)) {

if let match = rx.firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.count)) {

var result: [String] = Regex.stringMatches([match], text: string, index: index)
return result.count == 0 ? nil : result[0]

} else {

return nil

}

} catch {

return nil

}

}

// Match all occurrencies
static func pregMatchAll(_ string: String, regex: String, index: Int = 0) -> [String] {
do{

do {

let rx = try NSRegularExpression(pattern: regex, options: [.caseInsensitive])

var matches: [NSTextCheckingResult] = []
Expand All @@ -70,22 +70,22 @@ class Regex {

if string.count > limit {
string.split(by: limit).forEach {
matches.append(contentsOf: rx.matches(in: string, options: [], range: NSMakeRange(0, $0.count)))
matches.append(contentsOf: rx.matches(in: string, options: [], range: NSRange(location: 0, length: $0.count)))
}
} else {
matches.append(contentsOf: rx.matches(in: string, options: [], range: NSMakeRange(0, string.count)))
matches.append(contentsOf: rx.matches(in: string, options: [], range: NSRange(location: 0, length: string.count)))
}

return !matches.isEmpty ? Regex.stringMatches(matches, text: string, index: index) : []

} catch {

return []

}

}

// Extract matches from string
static func stringMatches(_ results: [NSTextCheckingResult], text: String, index: Int = 0) -> [String] {

Expand All @@ -97,14 +97,14 @@ class Regex {
return ""
}
}

}

// Return tag pattern
static func tagPattern(_ tag: String) -> String {

return "<" + tag + "(.*?)>(.*?)</" + tag + ">"

}

}
Loading

0 comments on commit c8ae80d

Please sign in to comment.