如何将数据保存到json文件并使用Alamofire发送到服务器

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

我想从服务器(本地apache)获取json文件,在UITextView中显示其内容,然后添加元素并上传回服务器。我在UITextView中加载了json内容,又添加了一个元素并转换为JSON类型。试图上传到服务器上,但没有上传文件。

我的加载数据代码:

func loadData() {
    AF.request("http://localhost/cheerfulNutApache/nuts.json", parameters: header).responseJSON { response in
        switch response.result {
            case .success(let value):
                let response = JSON(value)
                self.textView.text = "\(response)"

            case .failure(let error):
                print(error)
                break
        }
    }
}

我的上传代码:

let data = textView.text!

    let decode = JSON.init(parseJSON: data)
    print(type(of: decode))

    AF.request("http://localhost/cheerfulNutApache/swift.json", method: .post, parameters: decode).validate().response { (response) in
        switch response.result {
        case .success:
            print("Successful")
            print(response)
        case .failure(let error):
            print(error)
        }
    }

[我也用谷歌搜索这个问题,但是只找到如何上传图像而不是json。所以我需要一些帮助或建议

json swift server alamofire
1个回答
0
投票

基于Alamofire Documentations,要上传文件/数据,必须使用AF.upload(...) {...}代替AF.request(...) {...}

我认为您必须将上传代码更改为:

// Convert String to Data
//NOTE: this does NOT check text to be a valid JSON string.
let data = textView.text!.data(using: .utf8)!
let method: HTTPMethod = ... // Default value for `method` is `.post`.
let headers: HTTPHeaders = .../ If you have to set custom HTTP headers.

AF.upload(data, to: "http://localhost/cheerfulNutApache/swift.json", method: method, headers: headers)
  .validate()
  .response { (response) in

    ...

}

如果您的请求方法是.post,而不必设置HTTPHeaders,则只需使用此方法:

AF.upload(data, to: "http://localhost/cheerfulNutApache/swift.json")
    .validate()
    .response { (response) in

    ...

}

Editedupload方法的第二个参数应命名为to:。您也可以忽略将method设置为.post,因为method的默认值为.post

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