ios - 如何使用带委托(delegate)方法的 NSURLSession 连接到 Web 服务?

标签 ios xcode web-services swift nsurlsession

我尝试连接到 iOS 中的 Web 服务,但遇到了很多问题。我在这里找到了一个练习 Web 服务 - http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit

这段代码我已经写完了

    let soapMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
    "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
    "<soap:Body>\n"
    "<CelsiusToFahrenheit xmlns=\"http://www.w3schools.com/webservices/\">\n"
    "<Celsius>50</Celsius>\n"
    "</CelsiusToFahrenheit>\n"
    "</soap:Body>\n"
    "</soap:Envelope>\n"

    let url = NSURL(string: "http://w3schools.com/webservices/tempconvert.asmx")!

    var request = NSMutableURLRequest(URL: url)

    let messageLength = "\(soapMessage.utf16Count)"
    NSLog("\(messageLength)")
    request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.addValue("http://www.w3schools.com/webservices/CelsiusToFahrenheit", forHTTPHeaderField: "SOAPAction")
    request.addValue(messageLength, forHTTPHeaderField: "Content-Length")
    request.HTTPMethod = "POST"
    request.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

    var urlSession: NSURLSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())

它可以连接,但我的响应返回为 text/html 而不是 text/xml。我的问题是为什么它返回错误?我还要使用 NSURLSessionDataTask 还是 NSURLSessionDownloadTask?

最佳答案

对于您的情况,我认为它是 NSURLSessionDataTask。基于此站点:http://www.kaleidosblog.com/nsurlsession-in-swift-get-and-post-data

关于ios - 如何使用带委托(delegate)方法的 NSURLSession 连接到 Web 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26964845/

相关文章:

ios - 出现键盘时移动垂直居中的内容

ios - 单元格背景视差就像 iOS7 天气应用程序中一样

xcode - POD 错误。 Pod 依赖移除的\`pre_install\` 或\`post_install\`

ios - 由于 IBOutlets 而发生 SIGABRT 异常

web-services - 您能否帮助澄清有关 RESTful 服务和代码生成的一些要点?

web-services - 如何实现向后兼容的soap webservice(基于java)?

ios - 将 MKAnnotation 轻敲到 "select"真的很慢

iOS 今日扩展 : can this be dynamically enabled and disabled from within my app?

ios - Xcode 9.2 导出或导入 xliff 时崩溃

.net - 有没有办法测量 Web 服务响应的大小?