JSON 请求发送空数据(swift)

2024-04-12

我的 iOS 应用程序正在向 Web 服务发送空数据。我花了几个小时寻找解决方案,但没有任何效果。 应用程序应该通过 php 脚本将 kontrah 号码发送到数据库。然后数据库必须识别是否可以在数据库中找到 kontrah 编号。然后,如果数字正确,我会收到来自数据库服务器的请求。问题是我发送的号码肯定是正确的。我检查了发送到数据库的内容,结果都是空的:

{"kontrah":null,"telefon":null,"opis":null,"afakt":null}

我已经制作了相同的应用程序,但在 Android Studio 中使用 Java 运行,一切正常。

My Code:

@IBAction func submitAction(_ sender: AnyObject) {
    let kontrah: String = fkontrah.text!
     let telefon: String = ftelefon.text!



    let json = [ "kontrah" : (kontrah), "telefon" : (telefon), "opis" : (selectedvalue), "afakt" : (selectedafakt)  ]

    print (json)

    do {
        let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
        print(jsonData)
        // create post request
        let url = NSURL(string: "http://hetman.pl/ios/post2.php")!
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"

        // insert json data to the request
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData



        let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
            if error != nil{
                return
            }

            do {
                let t  = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
                print(t)

            } catch {
                print("Error  43-> \(error)")
            }
        }
        let alert = UIAlertController(title: "Wysłano poprawnie", message: "", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        self.present(alert, animated: true, completion: nil)


        task.resume()


    }

    catch {
        //handle error. Probably return or mark function as throws
        print(error)
        return
    }
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return(true)
}

}

Logs:

2017-12-29 15:59:43.867463+0100 Hetman4[10692:4029622] Failed to set (titleLabel.adjustsFontSizeToFitWidth) user defined inspected property on (UITextView): [<UITextView 0x7fa1ad829e00> valueForUndefinedKey:]: this class is not key value coding-compliant for the key titleLabel.
2017-12-29 15:59:47.717492+0100 Hetman4[10692:4029622] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/bartoszlucinski/Library/Developer/CoreSimulator/Devices/3BE9103E-97CA-4E0B-AE53-6196EE08C49D/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2017-12-29 15:59:47.717874+0100 Hetman4[10692:4029622] [MC] Reading from private effective user settings.
2017-12-29 15:59:52.225804+0100 Hetman4[10692:4029622] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 4072550144015629828_PortraitChoco_iPhone-Simple-Pad_Default
["telefon": "510356448", "kontrah": "1400-685", "opis": "Świnia", "afakt": "0"]
94 bytes
2017-12-29 15:59:57.074868+0100 Hetman4[10692:4029622] Failed to set (titleLabel.adjustsFontSizeToFitWidth) user defined inspected property on (UITextView): [<UITextView 0x7fa1b0096400> valueForUndefinedKey:]: this class is not key value coding-compliant for the key titleLabel.
2017-12-29 15:59:57.628832+0100 Hetman4[10692:4029622] Presenting view controllers on detached view controllers is discouraged <Hetman4.ViewController: 0x7fa1ac428ef0>.
Optional(["error": <null>, "result": kontrah  doesn't exist, "unAuthorizedRequest": 0, "success": 1])

PHP 脚本:

<?php
$kontrah = urlencode($_POST['kontrah']);
$telefon = urlencode($_POST['telefon']);
$opis = urlencode($_POST['opis']);
$afakt = urlencode($_POST['afakt']);

$url = 'https://hetman.e4b.com.pl/api/services/app/zlecenie/FormAddZlecenie?kontrah='.$kontrah.'&telefon='.$telefon.'&opis='.$opis.'&afakt='.&afakt;

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);


$results = curl_exec($ch);

curl_close($ch);
?>

有几个问题:

  1. 您的服务器正在等待application/x-www-form-urlencoded请求,而不是 JSON 请求。响应是 JSON,但请求不是。

  2. 当我使用hetman.plURL,但它正在重定向到www.hetman.pl,但替换POST with GET。当我直接发送请求到www.hetman.pl,我收到了不同的消息。不过,我无法阅读它们,所以我无法评论这是好还是坏。

  3. 与当前的问题无关,Swift 代码可以稍微整理一下,替换NSURL and NSURLRequest with URL and URLRequest, 分别。

把它们放在一起,你会得到类似的东西:

let parameters = ["kontrah" : kontrah, "telefon" : telefon, "opis" : selectedvalue, "afakt" : selectedafakt]

let url = URL(string: "http://www.hetman.pl/ios/post2.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setBodyContent(parameters)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print(error ?? "Unknown error")
        return
    }

    do {
        let t  = try JSONSerialization.jsonObject(with: data) as? [String:AnyObject]
        print(t ?? "Invalid")
    } catch {
        print("Error  43-> \(error)")
    }
}
task.resume()

Where

extension URLRequest {

    /// Populate the HTTPBody of `application/x-www-form-urlencoded` request
    ///
    /// - parameter parameters:   A dictionary of keys and values to be added to the request

    mutating func setBodyContent(_ parameters: [String : String]) {
        let parameterArray = parameters.map { (key, value) -> String in
            let encodedKey   = key.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
            let encodedValue = value.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
            return "\(encodedKey)=\(encodedValue)"
        }
        httpBody = parameterArray
            .joined(separator: "&")
            .data(using: .utf8)
    }
}

extension CharacterSet {

    /// Character set containing characters allowed in query value as outlined in RFC 3986.
    ///
    /// RFC 3986 states that the following characters are "reserved" characters.
    ///
    /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
    /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
    ///
    /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
    /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
    /// should be percent-escaped in the query string.
    ///
    /// - parameter string: The string to be percent-escaped.
    ///
    /// - returns: The percent-escaped string.

    static var urlQueryValueAllowed: CharacterSet = {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowed = CharacterSet.urlQueryAllowed
        allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)

        return allowed
    }()

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JSON 请求发送空数据(swift) 的相关文章

  • 无法显示由 Fine-uploader 上传到 Amazon s3 的图像

    我现在尝试设置fineuploader s3以显示在aws服务器上成功上传的文件的图像 如示例页面上所做的那样 http fineuploader com s3 demo http fineuploader com s3 demo 我 仍然
  • PHP别名@函数

    我是 PHP 新手 看到一些使用 前缀调用函数 如 mysql ping 的示例 我感到很困惑 它是做什么用的 谷歌搜索 搜索没有太大帮助 因为 被丢弃并且 别名 不是足够好的关键字 抑制错误 警告和通知 如果你用自定义的方式补充它 你可以
  • PHP 和 MySQL 的重音字符错误

    我的问题是 直接通过 PHP 编写的内容是正确重音的 但是当重音单词来自 MySQL 时 字母会像这样 我尝试使用html charset as ISO 8859 1它修复了 MySQL 字母 但破坏了其他字母 解决这一切的一种方法是设置我
  • 斯威夫特/iOS。从导航堆栈中删除一些视图控制器

    这是我想做的 但我不确定这是否是正确的方法 所以请给我建议如何去做 我有初始 VC 和导航 VC 我从中推送第一个 VC 从中推送第二个 VC 接下来我介绍 来自第二个 VC 的 NavigationController 第三个 VC 现在
  • iOS Safari 通过单击按钮触发扫描信用卡

    您好 我目前正在创建一个测试应用程序 当用户单击文本字段名称或卡号时 扫描信用卡功能对我有用 我的问题是 我希望当用户单击 button1 时发生同样的情况 这应该打开相机来扫描卡并填充现有的文本字段 即名称 卡号和到期日期 额外的好处是
  • 如何缓存 twitter api 结果?

    我想缓存 twitter api 结果的结果并将其显示给用户 缓存结果的最佳方法是什么 我正在考虑根据时间限制将结果写入文件 可以吗 还是应该使用任何其他方法 最重要的是 理想的缓存时间是多少 我想显示来自 twitter 的最新内容 但
  • gdb 声称它不知道如何运行

    我在 Mac Pro 上的 Mac OS X 10 6 6 上使用 Xcode 3 2 3 来构建 GrowlTunes 的修订版 5fd480ef577f咆哮开发存储库 http growl info hg growl developme
  • 在 PHP 中使用数组来比较用户名/密码

    我有以下 php 脚本 其中有一个用户名和密码 Username user1 Password pass1 if isset POST submitform Clean up the input values foreach POST as
  • 我应该使用排队系统来处理付款吗?

    我在用着Slim https www slimframework com和这个结合Stripe 的 PHP 库 https stripe com docs api php在我的应用程序中处理付款 一切都很好 但是直到最近 我在我的系统中发现
  • Swift 中的字典是否应该转换为类或结构?

    我正在开发一个本机 iOS 应用程序 该应用程序从我们也可以控制的 Web 服务接收 JSON 格式的数据 该计划是在大约 18 个月内更换后端数据库 以支持不同的平台 考虑到这一点 我们希望确保 iOS 应用程序能够相对容易地适应新的数据
  • 除括号之间的内容外,所有内容均小写

    考虑以下字符串 LoReM FOO IPSUM dolor BAR Samet fooBar 我正在寻找一种方法来小写所有内容 除了 brackets 之间的内容应该被忽略 所以期望的输出是 lorem FOO ipsum dolor BA
  • 连接 3 三张表

    我有这个图表应该可以解释我的情况 我需要一些关于连接 3 个表的帮助 我不知道如何做这种事情 因此 我可以通过执行以下操作来经历一段检索记录的 while 循环 img src alt Album AlbumID 使用内部联接 http w
  • 列出 JSON 的所有键和值

    假设我有一些如下所示的 JSON items item id 0001 type donut name Cake ppu 0 55 batters batter
  • 在 iPhone 中保存会话数据

    我想将数据存储在应用程序中的不同点 以便应用程序中的对象可以访问这些数据 类似于 php 中的 session 或全局变量 我知道我可以使用 NSUserDefaults 但我不确定如何继续向它添加值然后访问它 例如 首先我想存储登录期间使
  • Apple 允许后台任务运行多长时间?

    我必须将一系列图像文件上传到数据库 因此 我偶然发现苹果后台执行指南 https developer apple com library ios documentation iPhone Conceptual iPhoneOSProgram
  • AJAX:检查字符串是否为 JSON?

    我的 JavaScript 有时会在这一行崩溃 var json eval this responseText 当争论时会导致崩溃eval 不是 JSON 在进行此调用之前有什么方法可以检查字符串是否为 JSON 我不想使用框架 有什么方法
  • 如何判断handleOpenURL是在应用程序启动时调用还是在应用程序运行时调用?

    由于事件的顺序略有不同 具体取决于这两个场景中的哪一个正在进行 我希望能够区分出区别 有什么建议么 你不应该使用handleOpenURL因为它已被弃用 相反 使用application openURL sourceApplication
  • 表单提交后显示 $_FILES['image']

    提交表单后如何显示上传的图片 提交表单后 它将是一个预览页面 因此我不会在 MySQLet 中存储图像类型 BLOB 如何显示 FILES image
  • 通过 Apple 批量购买计划分发自定义 B2B iOS 应用程序?

    我们的要求是为组织内超过 1000 名用户分发 iOS 应用程序 我的问题 我们可以做吗使用 iOS Developer Provisioning Profile 分发 iPA 因为我们有 99 美元的 Apple 帐户 而不是企业帐户 并
  • PHP 中的简单 JSON 请求

    我有以下 json country code latitude 45 9390 longitude 24 9811 zoom 6 address city country Romania country code RO region 我只想

随机推荐

  • 检查列表是否包含类型?

    检查列表中是否存在某种类型的最快方法是什么 我希望我能做到以下几点 class Generic object def class SubclassOne Generic def class SubclassOne Generic def t
  • 如何处理 MVC 中的页面流(特别是 asp.net)

    如果您必须在 mvc 中提供类似于表单输入体验的向导 您将如何抽象页面流 研究重定向后获取模式 http weblogs asp net mhawley archive tags MVC default aspx http weblogs
  • sql 按日期分组,不带时间

    我是 sql 新手 我想创建一个查询来计算我每天的所有文章 ID 但问题是日期列也包含时间 那么我如何才能使查询仅按日期分组而无需时间 例如 id article id date timestamp 1 22 2014 01 10 13 3
  • GIT 不跟踪文件

    我已经在 AIX 6 1 上设置了 GIT 但遇到了问题 我遵循的步骤顺序如下所示 我创建一个文件夹 进入文件夹并初始化非裸存储库 初始化用户名和用户电子邮件 创建一个名为index html 的文件 并在该文件中包含一些数据 创建一个名为
  • 对小数的最快素数测试

    我在业余时间玩了 Euler 项目 现在我需要做一些重构 我已经实施了 Miller Rabin 以及一些筛子 我以前听说过 对于较小的数量 例如数百万以下 筛子实际上更快 有人有这方面的信息吗 谷歌并没有多大帮助 Yes you ll f
  • Tensorflow动态RNN(LSTM):如何格式化输入?

    我已获得这种格式的一些数据以及以下详细信息 person1 day1 feature1 feature2 featureN label person1 day2 feature1 feature2 featureN label person
  • 设置非 Office 文件的 Windows 文件属性

    我想在 NET 代码中设置文件的属性 我尝试过使用 DSOFile v2 1 如下所示 var properties new OleDocumentProperties try properties Open filePath proper
  • java中如何从字符串中提取子字符串

    亲爱的大家 我有一个像这样的字符串 1name john 2name lice 3name mike 我想输出它的子字符串 1name john 它在字符串中的位置不固定 我也使用子字符串方法但无法获取它 那么你能帮我一个忙吗 谢谢 Str
  • C# - 静态类型不能用作类型参数

    我有一个通用类可以帮助我检查参数值 internal sealed class Argument
  • Eclipse - 当涉及 Maven 时“作为 Java 应用程序运行”

    我有一个 Maven 项目 作为activeByDefault我有生产资料 看来我找不到使用临时配置文件在 Eclipse 中将其作为应用程序运行的方法 除非我将activeByDefault在暂存配置文件中 有没有办法配置这个 这样我就不
  • IE 脚本和通知设置之间的差异

    这些 IE 设置之间有什么区别 Disable script debugging Internet Explorer Disable script debugging Other Display a notification about e
  • 如何对这个(正确)抛出异常的异步方法进行单元测试?

    我在界面中有以下方法 Task
  • 使用 Javascript 进行速率限制并将 ajax 调用排队为每 15 秒一次

    我有一个应用程序 每次用户执行某些操作时都会自动发送推文 如果用户愿意 可以轻松地每秒执行一次该操作 Twitter 的速率限制表示 它关注 15 分钟内发生了多少条推文 从技术上讲 我认为我总是低于 15 分钟标记 但 Twitter 似
  • 如何处理 YARN MapReduce 作业的容器故障?

    YARN 中如何处理软件 硬件故障 具体来说 如果容器发生故障 崩溃 会发生什么 容器和任务失败由节点管理器处理 当容器失败或死亡时 节点管理器会检测到失败事件并启动一个新容器来替换失败的容器并在新容器中重新启动任务执行 如果应用程序主机发
  • 宏中参数的意外多重评估

    为什么第二个 printf 的输出是 max of 50 and 67 is 62 为什么 50 和 62 的最大值不是 57 define MAX a b a gt b a b int incr static int i 42 i 5 r
  • 无法使用实例引用访问成员“object.Equals(object, object)”;用类型名称来限定它

    当我在 C 中使用以下代码时 int totalValue 0 int total 0 totalValue int Parse Session price ToString int Parse Session day ToString T
  • TFS 合并:无法丢弃变更集

    我们有一个变更集 开发人员已签入对源分支和目标分支的更改 许多更改包括两个分支中的重命名 从源分支到目标分支的变更集合并进展顺利 但变更集仍保留在要合并的变更集列表中 当我现在尝试再次合并更改集时 它显示 没有要合并的更改 并且变更集保留在
  • 数组值不相同(但它们是?)

    我有两个数组 它们似乎包含至少一组相同的值 但执行array diff 即使我认为应该返回任何内容 也不会返回任何内容 这应该只是例行代码 但由于某种原因它不喜欢我所做的 奇怪的是var dump queue 0 回报String 167
  • 创建一个简单的 Makefile 来构建共​​享库

    我正在尝试创建一个非常基本的手工制作的 Makefile 来创建一个共享库来说明一点 这是我到目前为止所拥有的 SHELL bin sh CC gcc FLAGS std gnu99 Iinclude CFLAGS fPIC pedanti
  • JSON 请求发送空数据(swift)

    我的 iOS 应用程序正在向 Web 服务发送空数据 我花了几个小时寻找解决方案 但没有任何效果 应用程序应该通过 php 脚本将 kontrah 号码发送到数据库 然后数据库必须识别是否可以在数据库中找到 kontrah 编号 然后 如果