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



我想从服务器(本地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)

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

最新更新