如何使用 Alamofire.request() 将 XML soap 响应保存到文件?

How can I save an XML soap response to file using Alamofire.request()?

此函数向 SOAP API 发出请求,然后使用响应构建视图。我想缓存此响应以供离线使用。

func getUserFilesWithUserObj(userObj:User,completionhandler:@escaping (_ userFiles:NSArray, _ status: Bool) -> Void){
        let soapMessage: String = String(format: "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\"><soap12:Body><getFilesByID xmlns=\"http://example.com/\"><_usrID>%@</_usrID><_utStatus>%@</_utStatus></getFilesByID></soap12:Body></soap12:Envelope>",userObj.userId!,"9")

        guard let urlRequest = self.createSoapRequestFromSoapMessage(soapmessage: soapMessage) else{
            return
        }
        var localPath = AppDelegate.getDownloadFilesFolderPath()
        localPath = localPath.stringByAppendingPathComponent(path: "user-files")

        if FileManager.default.fileExists(atPath: localPath){
            do {
                self.processUserFiles(files: try String(contentsOf: NSURL(fileURLWithPath: localPath) as URL, encoding: .utf8))
            } catch let error as NSError { print(error) }
        }
        else{

            SwiftLoader.show(animated: true)
            Alamofire.request(urlRequest).responseData { (response) in
                SwiftLoader.hide()
                if response.error == nil{
                    if response.data != nil{
                        let strData = String(data: response.data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
                        do {
                            try strData?.write(to: NSURL(string: localPath)! as URL, atomically: false, encoding: .utf8)
                        } catch let error as NSError { print(error) }

                        self.processUserFiles(files: strData!)

                        completionhandler(self.arrUserTreatment!, true)
                    }
                    completionhandler(NSArray(), false)
                }
                else{
                    completionhandler(NSArray(), false)
                }
            }
        }
    }

这是我在 Xcode 终端中收到的错误消息,

2019-08-19 21:51:57.131031-0400 AppName[412:28510] CFURLCopyResourcePropertyForKey failed because it was passed an URL which has no scheme
Error Domain=NSCocoaErrorDomain Code=518 "The file couldn’t be saved because the specified URL type isn’t supported." UserInfo={NSURL=/var/mobile/Containers/Data/Application/AFFBB2E6-0EB9-4206-9AD5-EDB3AD22A23F/Documents/DownloadFiles/user-files}

如何将此响应中的 XML 保存到文件并稍后重新加载?

localPath 前添加 file:// 修复了错误。

var localPath = AppDelegate.getDownloadFilesFolderPath()
localPath = "file://" + localPath.stringByAppendingPathComponent(path: "user-files")

来源: