Image+fallback.swift (2512B)
1 /* MIT License 2 * 3 * Permission is hereby granted, free of charge, to any person obtaining a copy 4 * of this software and associated documentation files (the "Software"), to deal 5 * in the Software without restriction, including without limitation the rights 6 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 * copies of the Software, and to permit persons to whom the Software is 8 * furnished to do so, subject to the following conditions: 9 * 10 * The above copyright notice and this permission notice shall be included in all 11 * copies or substantial portions of the Software. 12 * 13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 * SOFTWARE. 20 * 21 */ 22 import SwiftUI 23 24 extension Image { 25 init(_ name: String, _ sysName: String, fallback: String = SYSTEM_DUMMY1) { 26 if let uiImage = UIImage(named: name) { 27 self.init(uiImage: uiImage) 28 } else if let sysImage = UIImage(systemName: sysName) { 29 self.init(uiImage: sysImage) 30 } else { 31 self.init(systemName: fallback) 32 } 33 } 34 35 /// Decode an `ImageDataUrl` as the protocol defines it: a data URL with an explicit 36 /// mediatype (`image/png` or `image/jpeg`) and the `base64` parameter. 37 /// Anything else must be rejected without ever being resolved: the string comes from 38 /// the merchant, and `NSData(contentsOf:)` would *fetch* an `http(s):` URL - blocking 39 /// the main thread and telling the merchant when (and how often) the user looks at 40 /// the transaction - or read a local file for a `file:` URL. 41 init?(imageBase64: String) { 42 let anchored: String.CompareOptions = [.caseInsensitive, .anchored] 43 guard let dataUrlPrefix = imageBase64.range(of: "data:image/png;base64,", options: anchored) 44 ?? imageBase64.range(of: "data:image/jpeg;base64,", options: anchored), 45 let data = Data(base64Encoded: String(imageBase64[dataUrlPrefix.upperBound...])), 46 let uiImage = UIImage(data: data) 47 else { return nil } 48 49 self.init(uiImage: uiImage) 50 } 51 }