swift4:
Sometimes a string has a prefix, such as data:image/png;base64,
, which will make base64Encoded
return nil
:
extension String { func base64ToImage() -> UIImage? { if let url = URL(string: self),let data = try? Data(contentsOf: url),let image = UIImage(data: data) { return image } return nil } }
full code:
extension String { func matches(for regex: String) -> [String] { do { let regex = try NSRegularExpression(pattern: regex) let results = regex.matches(in: self, range: NSRange(self.startIndex..., in: self)) return results.map { self.substring(with: Range($0.range, in: self)!) } } catch let error { print("invalid regex: \(error.localizedDescription)") return [] } } } let result = text.matches(for: "data:image\\/([a-zA-Z]*);base64,([^\\\"]*)") for imageString in result { autoreleasepool { let image = imageString.base64ToImage() } } }
hstdt source share