可以使用 AFHTTPRequestOperationManager 的 POST 方法来上传 JSON 字符串。首先需要将 JSON 字符串转换为 NSData 对象,然后使用 POST 方法将其上传。

下面是一个示例代码:

import AFNetworking

let manager = AFHTTPRequestOperationManager()
manager.requestSerializer = AFJSONRequestSerializer()

let jsonString = '{"name":"John","age":30,"city":"New York"}'
if let jsonData = jsonString.data(using: .utf8) {
    manager.POST("http://example.com/upload", parameters: nil, constructingBodyWith: { (formData: AFMultipartFormData!) -> Void in
        formData.appendPart(withFileData: jsonData, name: "file", fileName: "data.json", mimeType: "application/json")
    }, success: { (operation: AFHTTPRequestOperation!, responseObject: Any!) -> Void in
        // 上传成功
        print("上传成功")
    }, failure: { (operation: AFHTTPRequestOperation!, error: Error!) -> Void in
        // 上传失败
        print("上传失败: (error.localizedDescription)")
    })
}

在上面的代码中,首先创建一个 AFHTTPRequestOperationManager 对象,并将其 requestSerializer 设置为 AFJSONRequestSerializer,这样可以确保上传的数据格式为 JSON。

然后,将 JSON 字符串转换为 NSData 对象,并使用 POST 方法将其上传到指定的 URL。在 constructingBodyWith 闭包中,可以使用 formData.appendPart 方法将 NSData 对象添加到请求中,并指定 name、fileName 和 mimeType。

最后,通过 success 和 failure 闭包来处理上传结果。

Swift 使用 AFNetworking 上传 JSON 字符串

原文地址: https://www.cveoy.top/t/topic/p06k 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录