Commit a8178111 by Sarkizz

添加前端DataURL解析

parent 2b5ea931
......@@ -9,6 +9,8 @@
import Foundation
import CommonCrypto
// MARK: - MD5签名
extension String {
public var md5: String {
let data = Data(self.utf8)
......@@ -21,12 +23,20 @@ extension String {
}
}
// MARK: - Base64
extension String {
public var base64Data: Data? {
return Data(base64Encoded: self, options: NSData.Base64DecodingOptions())
}
}
struct Constants {
public static let moblieNumberRegex = "^1\\d{10}$"
public static let emailRegex = "^[A-Za-z0-9._%+-\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"
public static let phoneNumberRegex = "^\\d{3,4}-?\\d{4,8}$"
}
// MARK: - 字符串常用判断
extension String {
/// 是否电话号码(固话+手机号码)
public var isPhoneNumber: Bool {
......@@ -75,6 +85,7 @@ public enum MRStringAttribute {
case link(NSURL)
}
// MARK: - Attribute
extension String {
public func attribute(_ attrs: MRStringAttribute ..., range: NSRange? = nil) -> NSMutableAttributedString {
return attribute(attrs, range: range)
......@@ -148,3 +159,62 @@ extension String {
return text.boundingRect(with: fixedSize, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil).size
}
}
// MARK: - Data URL
extension String {
public enum DataURLContentType: String {
case image_jpeg = "image/jpeg"
case image_png = "image/png"
}
public enum DataURLDataType: String {
case base64 = "base64"
case string = "string"
}
struct DataURLInfo {
var contentType: DataURLContentType
var dataType: DataURLDataType
var data: String
}
public func parserDataURL() -> Any? {
if let info = dataInfo {
switch info.contentType {
case .image_jpeg, .image_png:
return convertToImage(info)
}
}
return nil
}
}
extension String {
private var dataInfo: DataURLInfo? {
if self.hasPrefix("data:") {
var temp = self
temp = temp.replacingOccurrences(of: "data:", with: "")
let split = temp.split(separator: ";").map({ String($0) })
if split.count == 2, let contentType = DataURLContentType(rawValue: split[0]) {
let split = split[1].split(separator: ",").map({ String($0) })
if split.count == 2, let dataType = DataURLDataType(rawValue: split[0]) {
return DataURLInfo(contentType: contentType, dataType: dataType, data: split[1])
}
}
}
return nil
}
private func convertToImage(_ info: DataURLInfo) -> UIImage? {
switch info.dataType {
case .base64:
if let data = base64Data {
return UIImage(data: data)
}
default:
return nil
}
return nil
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment