I am getting base64 images in an API call and I need to store these as files locally.
I was trying to write this data without having to convert the string to UIImage and then UIImage to JPEGRepresentation.
I don't want the overhead of creating UIImages first and theen changing to JPEGs if I can avoid it, but I don't know if this is possible?
I can see in my app Container, that all the files are there and the correct filesize but when I try to open them, they won't and I am told they may be corrupt.
extension NSData {
func writeToURL2(named:URL, completion: @escaping (_ result: Bool, _ url:NSURL?) -> Void) {
let tmpURL = named as NSURL
DispatchQueue.global(qos: .background).async { [weak self] () -> Void in
guard let strongSelf = self else { completion (false, tmpURL); return }
strongSelf.write(to: tmpURL as URL, atomically: true)
var error:NSError?
if tmpURL.checkResourceIsReachableAndReturnError(&error) {
print("We have it")
completion(true, tmpURL)
} else {
print("We Don't have it\(error?.localizedDescription)")
completion (false, tmpURL)
}
}
}
}
and it is used like:
for employee in syncReponse
{
autoreleasepool{
if let employeeJsonStr = employee["data"] as? String{
if let employeeDataDict = try? JSONSerializer.toDictionary(employeeJsonStr), let proPic = employeeDataDict["profilepicture"] as? String, proPic.removingWhitespaces() != "", let idStr = employeeDataDict["employeeId"] as? String, let proPicData = (proPic.data(using: .utf8)) {
let empPicDir = mainDir.appendingPathComponent(util_Constants.DIR_EMP_PICS)
let filename = empPicDir.appendingPathComponent(idStr+".jpg")
(proPicData as NSData).writeToURL2(named: filename, completion: { (result, url) -> Void in
})
}
let Emp = DATA_EP_employee(employeeJsonStr : employeeJsonStr)
dataList.append(Emp)
reqCount += 1
}
}
}