Skip to content

Instantly share code, notes, and snippets.

@saud978
Created February 5, 2024 10:49
Show Gist options
  • Save saud978/d24714df234553afc06ed46fb0905109 to your computer and use it in GitHub Desktop.
Save saud978/d24714df234553afc06ed46fb0905109 to your computer and use it in GitHub Desktop.
import UIKit
import CommonCrypto
//MARK: - String extentions
extension String {
var isValidURL: Bool {
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
if let match = detector.firstMatch(in: self, options: [], range: NSRange(location: 0, length: self.utf16.count)) {
// it is a link, if the match covers the whole string
return match.range.length == self.utf16.count
} else {
return false
}
}
/// Encrypt a string using SHA1 encrtyption.
/// - Returns: Encrypted String
func sha1() -> String {
let data = Data(self.utf8)
var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_SHA1($0.baseAddress, CC_LONG(data.count), &digest)
}
let hexBytes = digest.map { String(format: "%02hhx", $0) }
return hexBytes.joined()
}
}
extension String {
/// Remove leading spaces from String
/// - Returns: String
func removingLeadingSpaces() -> String {
guard let index = firstIndex(where: { !CharacterSet(charactersIn: String($0)).isSubset(of: .whitespaces) }) else {
return self
}
return String(self[index...])
}
/// Remove all extra spaces in String (every two spaces converted to one)
/// - Returns: String
func removeWhitespace() -> String {
return self.replacingOccurrences(of: " ", with: " ")
}
}
extension String {
/// Check if string contian Arabic letters and return bool
var isArabic: Bool {
let predicate = NSPredicate(format: "SELF MATCHES %@", "(?s).*\\p{Arabic}.*")
return predicate.evaluate(with: self)
}
}
extension String {
/// Convert numbers from Arabic to Hindi
/// - Returns: Converted Hindi Number as String
func convertToHindiNumbers () -> String? {
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "EN")
guard let number = formatter.number(from:self ) else {return nil}
formatter.locale = Locale(identifier: "AR")
guard let arabicNumbers = formatter.string(from: number) else{
return nil
}
return arabicNumbers
}
}
extension String{
/// Encode URL
/// - Returns: Encoded URL
func encodeUrl() -> String
{
return self.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed) ?? ""
}
/// Decode URL
/// - Returns: Decoded URL
func decodeUrl() -> String
{
return self.removingPercentEncoding ?? ""
}
/// Check if string has a valid URL Scheme
/// - Returns: Bool
func isValidForUrl() -> Bool{
if(self.hasPrefix("http") || self.hasPrefix("https")){
return true
}
return false
}
}
//MARK: - UIView extensions
extension UIView {
/// This function create an image from a UIView and all its content
/// - Returns: UIImage for the whole view and all its content
func asImage() -> UIImage {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
}
}
//MARK: - UIButton extensions
/// Add border to UIButton like the buttons on AppStore
/// For best result use
/// Border Witdh = 1
/// Corner Radius = 4
/// Border Color = hex (#0076FF)
@IBDesignable extension UIButton {
@IBInspectable var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
self.contentEdgeInsets.top = 5
self.contentEdgeInsets.bottom = 5
self.contentEdgeInsets.right = 5
self.contentEdgeInsets.left = 5
}
get {
return layer.borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}
@IBInspectable var borderColor: UIColor? {
set {
guard let uiColor = newValue else { return }
layer.borderColor = uiColor.cgColor
}
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
}
}
//MARK: - UIIMage
extension UIImage {
var isPortrait: Bool { return size.height > size.width }
var isLandscape: Bool { return size.width > size.height }
var breadth: CGFloat { return min(size.width, size.height) }
var breadthSize: CGSize { return CGSize(width: breadth, height: breadth) }
var breadthRect: CGRect { return CGRect(origin: .zero, size: breadthSize) }
func rounded(with color: UIColor, width: CGFloat) -> UIImage? {
let bleed = breadthRect.insetBy(dx: -width, dy: -width)
UIGraphicsBeginImageContextWithOptions(bleed.size, false, scale)
defer { UIGraphicsEndImageContext() }
guard let cgImage = cgImage?.cropping(to: CGRect(origin: CGPoint(
x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,
y: isPortrait ? ((size.height-size.width)/2).rounded(.down) : 0),
size: breadthSize))
else { return nil }
UIBezierPath(ovalIn: CGRect(origin: .zero, size: bleed.size)).addClip()
var strokeRect = breadthRect.insetBy(dx: -width/2, dy: -width/2)
strokeRect.origin = CGPoint(x: width/2, y: width/2)
UIImage(cgImage: cgImage, scale: 1, orientation: imageOrientation).draw(in: strokeRect.insetBy(dx: width/2, dy: width/2))
color.set()
let line = UIBezierPath(ovalIn: strokeRect)
line.lineWidth = width
line.stroke()
return UIGraphicsGetImageFromCurrentImageContext()
}
}
extension UIImageView {
func loadFrom(URLAddress: String) {
guard let url = URL(string: URLAddress) else {
return
}
DispatchQueue.main.async { [weak self] in
if let imageData = try? Data(contentsOf: url) {
if let loadedImage = UIImage(data: imageData) {
self?.image = loadedImage
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment