ios - 来自 swift 前端的 POST 请求问题

标签 ios json swift flask

我正在尝试实现 Swift 前端,以便它可以将数据上传到数据库,该数据库是通过 Flask 用 Python 编写的,并使用 PostgreSQL。我用于发送 POST 请求的前端 Swift 代码目前如下所示,如果重要的话,它是在 View Controller 中编写的:

func PostData(){

        let parameters:[String: Any]=["latitude":  35.0094040,
                        "longitude": -85.3275640,
                        "tag": "this is my fancy tag",
                        "image":"icecream.jpg"]
        let jsonURLString="http://localhost/api/tags"
        guard let url=URL(string: jsonURLString) else{
            return
        }
        var request=URLRequest(url: url)
        request.httpMethod="POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        guard let httpBody=try? JSONSerialization.data(withJSONObject: parameters, options: [])  else{
            return
        }
        request.httpBody=httpBody
        let session=URLSession.shared
        session.dataTask(with: request) { (data, _, error) in


            if let data=data{
                do{
                    try JSONSerialization.jsonObject(with: data, options: [])  
                }catch{
                    print(error)
                }
            }
            }.resume()
    }

我接受post请求的后端代码如下:

@app.route('/api/tags',  methods=  ["GET",  "POST"])
def get_tags_api():
    if request.method == "POST":
        latitude  =  request.form.get("latitude")
        longitude  =  request.form.get("longitude")
        text  =  request.form.get("tag")
        image_  =  request.form.get("image", None)
        print (latitude)
        print (longitude)
        print (text) 
        print (image_)
        create_tags(latitude=latitude, longitude=longitude, text=text, image=image_)

当我尝试运行以下代码时,我从 Xcode 收到以下错误消息:

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

在后端,所有变量都打印为 None,并显示以下错误消息:

[SQL: INSERT INTO tags (text, longitude, latitude, image) VALUES (%(text)s, %(longitude)s, %(latitude)s, %(image)s) RETURNING tags.id]
[parameters: {'text': None, 'longitude': None, 'latitude': None, 'image': None}]
(Background on this error at: http://sqlalche.me/e/gkpj)

鉴于前端PostData函数运行时后端显示错误消息,请求一定已经发送,但后端没有检测到请求中的任何数据,我不知道为什么会这样。我不确定我在这里做错了什么。我是 Swift 的新手,而且我对 Flask 没有太多经验。请帮忙。

最佳答案

我认为你的代码是错误的。

guard let httpBody=try? JSONSerialization.data(withJSONObject: parameters, options: [])  else {
     return
}

可以引用Alamofire - ParameterEncoding.swift

关于ios - 来自 swift 前端的 POST 请求问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56943509/

相关文章:

ios - 如何在Swift 3中禁用选项卡栏的用户交互?

ios - 跳出 UINavigationBar 后获取 UITabBar

java - 如何将 Mule ESB 中的数据映射器转换为多个连接器以使用社区运行时?

c# - 使用 C# 的 crunchbase API 中的日期时间格式问题

swift - 我可以在 UserDefaults 上存储哪种类型的字典或数组有任何限制吗?

ios - Swift3 - UICollectionViewCel 的 intrinsicContentSize 是 (-1, -1)

ios - 如何在 iOS 中显示带有天气信息的通知横幅?

iphone - NSZombieEnabled 似乎修复了我的错误

iphone - 在 nsuserdefaults 中保存复选标记附件值,然后检索它们

java - 使用 Spring RestTemplate 将 JSONP 转换为 JSON