为什么不能在swift中将JSON发布到服务器?

问题描述 投票:0回答:1

我能够通过POSTMAN将param JSON发布到服务器,但不能在这个快速代码中发布它。为什么?

我的控制台有这个错误

A1AD-41C2-955D-4E000D35C5CC>。<4>表示错误 - 代码:-1002

let param = [["cid": "5","accbookname" : "fromiOS2","accbooktype": "test","category": "test","user": "test"]] as [[String : Any]]

    let headers = [
        "content-type": "application/json",
        "cache-control": "no-cache"
    ]

    if let postData = (try? JSONSerialization.data(withJSONObject: param, options: [])) {
        let serverUrl = "x-cow.com/finnciti/scripts/updateAccountBook.php"
        let request = NSMutableURLRequest(url: URL(string: serverUrl)!,
                                          cachePolicy: .useProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody = postData

        print(String(data: postData, encoding: .utf8)!)
        //[{"cid":"5","user":"test","accbooktype":"test","accbookname":"fromiOS2","category":"test"}]
        //can post this on postman

        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            (data, response, error) -> Void in
            DispatchQueue.main.async(execute: {
                if error != nil {
                    print("failed!!!\(error!.localizedDescription)")
                    //failed!!!unsupported URL
                    return
                }
....

enter image description here

[{"cid":"5","user":"test","accbooktype":"test","accbookname":"fromiOS2","category":"test"}]
json swift
1个回答
0
投票

我认为你的URL不正确。

尝试在http://和最终的URL之前添加URL

http://x-cow.com/finnciti/scripts/updateAccountBook.php

编辑:

我用它测试了你的代码并且它正在运行。检查下面的截图:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.