Swift Base 64字符串直接转换为文件系统上的Jpeg

时间:2019-04-15 14:54:11

标签: ios swift uiimage base64 uiimagejpegrepresentation

我正在通过API调用获取base64图像,我需要将这些图像存储为本地文件。

我试图写入数据,而不必将字符串转换到UIImage ,然后然后将UIImage转换为 JPEG表示形式

我不希望先创建UIImage并在可以避免的情况下将其更改为JPEG的开销,但是我不知道这样做是否可行?

我可以在我的应用容器中看到所有文件都在那里,并且文件大小正确,但是当我尝试打开它们时,它们不会,并且被告知它们可能已损坏。

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)
            }

        }

    }
}

它的用法类似于:

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
                    }
                }
            }

0 个答案:

没有答案