【问题标题】:How to save data to json file and send to server with Alamofire如何将数据保存到 json 文件并使用 Alamofire 发送到服务器
【发布时间】:2020-03-22 16:59:33
【问题描述】:

我想从服务器(本地 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。所以我需要一些帮助或建议。

UPD:添加AF上传功能输出

[Request]: POST http://localhost/cheerfulNutApache/swift.json
[Request Body]: 
None
[Response]: 
[Status Code]: 200
[Headers]:
Accept-Ranges: bytes
Connection: Keep-Alive
Content-Length: 0
Content-Type: application/json
Date: Mon, 23 Mar 2020 17:29:31 GMT
Etag: "0-5a188e7f87fc0"
Keep-Alive: timeout=5, max=100
Last-Modified: Mon, 23 Mar 2020 17:24:23 GMT
Server: Apache/2.4.41 (Unix) PHP/7.3.9
[Response Body]: 
None
[Data]: None
[Network Duration]: 0.08196401596069336s
[Serialization Duration]: 0.0s
[Result]: success(nil)
Swift.Result<Swift.Optional<Foundation.Data>, Alamofire.AFError>.success(nil)

【问题讨论】:

  • 在这里您尝试将 json 发布到服务器。要上传一个 json 文件是不同的,你必须上传为 formdata 多部分。

标签: json swift server alamofire


【解决方案1】:

基于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

    ...

}

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

【讨论】:

  • 我试过你的代码,但 Xcode 说除了数据和 URL 之外我不能添加任何其他功能
  • 使用AF的版本是多少?
  • AF 版本 5.0.2
  • 糟糕!方法的第二个参数应该命名为to:。我编辑了我的答案。看看吧。
  • 我收到一个错误:对成员'upload(_:to:method:headers:interceptor:fileManager:)'的模糊引用。可能是AF版本的原因?
猜你喜欢
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
  • 2018-01-20
  • 1970-01-01
  • 2019-03-30
  • 2012-12-22
  • 2011-09-02
  • 1970-01-01
相关资源
最近更新 更多