Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在Swift中使用Alamofire处理XML数据_Ios_Xml_Swift_Alamofire - Fatal编程技术网

Ios 在Swift中使用Alamofire处理XML数据

Ios 在Swift中使用Alamofire处理XML数据,ios,xml,swift,alamofire,Ios,Xml,Swift,Alamofire,我开始在当前的ios项目中使用cocoapods。我需要使用SOAP以简单的方式为我的ios项目获取内容。我已经在谷歌上搜索过了,阿拉莫菲尔吊舱对我来说很棒。因为我使用的是Swift编程语言 我已经很容易地初始化了这个豆荚。但我的web服务返回XML结果。我想序列化来排列这个XML结果。但我不能 当我用浏览器调用我的web服务时,我得到了这种结果 Alamofire响应方法如下所示: Alamofire.request(.GET, "http://my-web-service-domain.c

我开始在当前的ios项目中使用cocoapods。我需要使用SOAP以简单的方式为我的ios项目获取内容。我已经在谷歌上搜索过了,阿拉莫菲尔吊舱对我来说很棒。因为我使用的是Swift编程语言

我已经很容易地初始化了这个豆荚。但我的web服务返回XML结果。我想序列化来排列这个XML结果。但我不能

当我用浏览器调用我的web服务时,我得到了这种结果

Alamofire响应方法如下所示:

Alamofire.request(.GET, "http://my-web-service-domain.com", parameters: nil)
         .response { (request, response, data, error) in
                     println(request)
                     println(response)
                     println(error)
                   }
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">{"Response":{"Status":"success","Result_Count":"1","Error_Description":"","Result":{"Login_result":{"user_id":"1","user_type":"1","user_name":"h4cked","user_locked":"False","user_locked_message":""}}}}</string>
import XMLCoder

...

dataRequest
    .validate()
    .responseDecodable(of: T.self, decoder: XMLDecoder()) { (response: DataResponse<T, AFError>) in
        
当我运行此方法时,我在终端上看到以下输出:

<NSMutableURLRequest: 0x170010a30> { URL: http://my-web-service-domain.com }
Optional(<NSHTTPURLResponse: 0x1704276c0> { URL: http://my-web-service-domain.com } { status code: 200, headers {
    "Cache-Control" = "private, max-age=0";
    "Content-Length" = 1020;
    "Content-Type" = "text/xml; charset=utf-8";
    Date = "Thu, 18 Jun 2015 10:57:07 GMT";
    Server = "Microsoft-IIS/7.5";
    "X-AspNet-Version" = "2.0.50727";
    "X-Powered-By" = "ASP.NET";
} })
nil
{URL:http://my-web-service-domain.com }
可选({URL:http://my-web-service-domain.com }{状态代码:200,标题{
“缓存控制”=“专用,最大使用年限=0”;
“内容长度”=1020;
“内容类型”=“文本/xml;字符集=utf-8”;
日期=“2015年6月18日星期四10:57:07 GMT”;
Server=“Microsoft IIS/7.5”;
“X-AspNet-Version”=“2.0.50727”;
“X-Powered-By”=“ASP.NET”;
} })
无
我想得到一个数组的结果,该数组在浏览器上显示我的故事板。
有谁能帮我用Alamofire framework或Swift语言序列化这些数据吗?

如果我没有误解您的描述,我想您应该获取XML数据并对其进行解析,对吗?关于这一点,您可能会在响应回调中处理错误的变量。您应该
println(data)
来检查XML文档

解析XML数据时,可以考虑。Alamofire请求可能如下所示:

Alamofire.request(.GET, "http://my-web-service-domain.com", parameters: nil)
         .response { (request, response, data, error) in
            println(data) // if you want to check XML data in debug window.
            var xml = SWXMLHash.parse(data!)
            println(xml["UserDTO"]["FilmID"].element?.text) // output the FilmID element.
         }

有关XML管理的更多信息,请使用截至2015年9月的Alamofire 3.0当前版本和Xcode 7进行检查。

下面的实现的优点是不使用额外的外部库,如SWXMLHash

Alamofire.request(.GET, urlString, encoding: .PropertyList(.XMLFormat_v1_0, 0)).responsePropertyList { request, response, result in

//Note that result have two properties: error and value as of Alamofire 3.0, check the migration guide for more info

  if let error = result.error {
    print("Error: \(error)")

    // parsing the data to an array 
  } else if let array = result.value as? [[String: String]] {

    if array.isEmpty {
      print("No data")

    } else { 
      //Do whatever you want to do with the array here
    }
  }
}

阿拉莫菲尔4.x-Swift 3.x

(请注意,在本例中,我使用了
URLEncoding.default
而不是
URLEncoding.xml
,因为
xml
参数排除了传递参数和标题的可能性,所以
default
更容易理解。)


根据3.0.0-beta.3和

对我来说,正确的语法是:

Alamofire.request(.GET, url, parameters: params, encoding: ParameterEncoding.URL).responsePropertyList { response in

            if let error = response.result.error {
                print("Error: \(error)")

                // parsing the data to an array
            } else if let array = response.result.value as? [[String: String]] {

                if array.isEmpty {
                    print("No data")

                } else { 
                    //Do whatever you want to do with the array here
                }
            }
        }
如果您想要一个好的XML解析器,请查看

例如:
let xml=SWXMLHash.parse(string)

我遇到了一个非常独特的问题,服务器返回了一个以JSON作为字符串的xml。希望它能帮助别人

XML基本上如下所示:

Alamofire.request(.GET, "http://my-web-service-domain.com", parameters: nil)
         .response { (request, response, data, error) in
                     println(request)
                     println(response)
                     println(error)
                   }
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">{"Response":{"Status":"success","Result_Count":"1","Error_Description":"","Result":{"Login_result":{"user_id":"1","user_type":"1","user_name":"h4cked","user_locked":"False","user_locked_message":""}}}}</string>
import XMLCoder

...

dataRequest
    .validate()
    .responseDecodable(of: T.self, decoder: XMLDecoder()) { (response: DataResponse<T, AFError>) in
        

tsaiid在Swift 3和Alamofire 4中的回答:

Alamofire.request("http://my-web-service-domain.com", parameters: nil) //Alamofire defaults to GET requests
     .response { response in
        if let data = response.data {
          println(data) // if you want to check XML data in debug window.
          var xml = SWXMLHash.parse(data)
          println(xml["UserDTO"]["FilmID"].element?.text) // output the FilmID element.
        }
     }

如果您想将XML映射到Swift对象,您也可以考虑。(使用与相同的技术)

通过实现
XMLMappable
协议创建您的模型:

class UserDTO: XMLMappable {
    var nodeName: String!

    var extensionData: String?
    var canChangeDeviceConfig: BooleanAtttribute?
    var canChangeDriverConfig: BooleanAtttribute?
    var canChangeFleetConfig: BooleanAtttribute?
    var canChangeGeofenceConfig: BooleanAtttribute?
    var canSaveHistory: BooleanAtttribute?
    var canViewReport: BooleanAtttribute?
    var canWatchHistory: BooleanAtttribute?
    var deliverDailyReportByEmail: BooleanAtttribute?
    var deliverDailyReportBySms: BooleanAtttribute?
    var email: String?
    var firm: String?
    var firmId: Int?
    var firstName: String?
    var id: Int?
    var isActive: Bool?
    var isAdmin: Bool?
    var lastName: String?
    var phone: String?
    var recivesDailyReport: BooleanAtttribute?
    var userName: String?

    required init(map: XMLMap) {

    }

    func mapping(map: XMLMap) {
        extensionData <- map["ExtensionData"]
        canChangeDeviceConfig <- map["CanChangeDeviceConfig"]
        canChangeDriverConfig <- map["CanChangeDriverConfig"]
        canChangeFleetConfig <- map["CanChangeFleetConfig"]
        canChangeGeofenceConfig <- map["CanChangeGeofenceConfig"]
        canSaveHistory <- map["CanSaveHistory"]
        canViewReport <- map["CanViewReport"]
        canWatchHistory <- map["CanWatchHistory"]
        deliverDailyReportByEmail <- map["DeliverDailyReportByEmail"]
        deliverDailyReportBySms <- map["DeliverDailyReportBySms"]
        email <- map["Email"]
        firm <- map["Firm"]
        firmId <- map["FirmId"]
        firstName <- map["FirstName"]
        id <- map["Id"]
        isActive <- (map["IsActive"], BooleanTransformeType(trueValue: "true", falseValue: "false"))
        isAdmin <- (map["IsAdmin"], BooleanTransformeType(trueValue: "true", falseValue: "false"))
        lastName <- map["LastName"]
        phone <- map["Phone"]
        recivesDailyReport <- map["RecivesDailyReport"]
        userName <- map["UserName"]
    }
}

class BooleanAtttribute: XMLMappable {
    var nodeName: String!

    var booleanValue: Bool?

    required init(map: XMLMap) {

    }

    func mapping(map: XMLMap) {
        booleanValue <- (map.attributes["xsi:nil"], BooleanTransformeType(trueValue: "true", falseValue: "false"))
    }
}

class Firm: XMLMappable {
    var nodeName: String!

    var extensionData: String?
    var firmTypeId: Int?
    var id: Int?
    var name: String?
    var parentFirmId: Int?

    required init(map: XMLMap) {

    }

    func mapping(map: XMLMap) {
        extensionData <- map["ExtensionData"]
        firmTypeId <- map["FirmTypeId"]
        id <- map["Id"]
        name <- map["Name"]
        parentFirmId <- map["ParentFirmId"]
    }
}

class BooleanTransformeType<T: Equatable>: XMLTransformType {
    typealias Object = Bool
    typealias XML = T

    private var trueValue: T
    private var falseValue: T

    init(trueValue: T, falseValue: T) {
        self.trueValue = trueValue
        self.falseValue = falseValue
    }

    func transformFromXML(_ value: Any?) -> Bool? {
        if let value = value as? T {
            return value == trueValue
        }
        return nil
    }

    func transformToXML(_ value: Bool?) -> T? {
        if value == true {
            return trueValue
        }
        return falseValue
    }
}
或者,您可以使用SubSec和
responseXMLObject(completionHandler:)
函数将响应直接映射到模型对象:

let userDTO = XMLMapper<UserDTO>().map(XMLString: xmlString)
Alamofire.request("http://my-web-service-domain.com", method: .get).responseXMLObject { (response: DataResponse<UserDTO>) in
    let userDTO = response.result.value
    print(userDTO?.id ?? "nil")
}
Alamofire.request(“http://my-web-service-domain.com,方法:.get).responseXMLObject{(响应:DataResponse)位于
让userDTO=response.result.value
打印(userDTO?.id??“nil”)
}

我希望这是有用的。

如果您需要在Alamofire上使用不同的解码器(JSON、URL、XML)
,我发现最好最简单的方法就是使用

  • 阿拉莫菲尔5号
  • Swift 5
(它可能适用于较旧的版本)


在Alamofire的响应可解码方法中,您只需要使用XMLDecoder()


我创建了一个GIST,其中包含如何使用Alamofire解码XML的完整结构,并添加了一些带有嵌套对象和XML属性的示例



这是最好的答案。与alamofire 3配合使用,效果良好。但我的回答没有什么特别之处。所以它给了我一个异常“致命错误:在展开可选值时意外地发现了nil”。我如何解决它?还有Alamofire 4.5?我以为你有一个神奇的方法通过Alamofire解析它,而不是使用第三部分API:XYou可以将编码留空,不会有任何改变。这不是答案。这个库在这里被多次提到。@6rchid你是说一个旧的答案(5年前),所以你不能用现代的编译器和当前的情况来分析代码。在那个时期,该库是处理XML的最佳库,今天我们身处另一个世界,先生。下次请求帮助时,这应该比在没有正当理由的情况下降级最旧的帖子更有用。swift 3没有println
import Foundation

class ReportModel: Codable {
    var connections: ConnectionModel?
    var notifications: NotificationsModel?

    enum CodingKeys: String, CodingKey {
        case connections
        case notifications
    }
}