ios - swift ios 使用 alamofire 将 curl 转换为 swift curl

标签 ios swift curl header alamofire

我在下面有我的 curl 我想使用 alamofire 作为发布请求快速执行它,有人有想法吗?我的代码有什么问题。

curl curl -H "Content-Type: application/json"      -H "Authorization: Bearer 05BE1EA85FDC05919A37ADF7E93fF518"      -X POST "https://b28831d6-7859-4e19f-a929-7ec4b73f6acb.pushnotifications.pusher.com/publish_api/v1/instances/b28d831d6-7859-4e19-a929-7ec4b73f6acb/publishes"      -d '{"interests":["hello"],"apns":{"aps":{"alert":{"title":"Hello","body":"Hello, world!"}}}}'
{"publishId":"pubid-fc883ab1-0c7f-420a-b864-7ccb1c04cc78"}
4LOOP-MAC-MINI:Fridgeboard_iOS-master-2 test.tesst$ 

一个

lamofire code

 func sendTextToServer(text: String) {
//    
        let headers:HTTPHeaders = ["Authorization": "Bearer 05BE1EA85FDC05919A37ADF7E9d3F518", "Content-Type": "application/json"]

//
        let parameters: Parameters = "["interests":["hello"],"apns":["aps":["alert":"title":"Hello","body":"Helloworld!"]"


        Alamofire.request("https://b28831d6-785d9-4e19-a929-7ec4b73f6acb.pushnotifications.pusher.com/publish_api/v1/instances/b28831d6-7859-4e19-a929-7ec4b73f6dacb/publishes", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in

            if let dictionary = response.result.value as? Dictionary<String,AnyObject> {
                let json = JSON(dictionary)
//                if let textToSpeech = json["result"]["fulfillment"]["speech"].string {
//                    self.speakText(text: t    extToSpeech)
//                }
            }
        }

    }

最佳答案

您应该尝试使用 Custom Per Request Header。

为您的自定义标题创建字典:

let headers: HTTPHeaders = ["Accept": "application/json"]

HTTPHeaders 只是一个字符串字典:

public typealias HTTPHeaders = [String: String]

然后将 header 作为参数传递到您的调用中以创建请求:

// In the empty quotes, enter you API url info.
let urlString = "" Alamofire.request(urlString, headers: headers).responseJSON { ... } 

要确保您的 header 已发送,您可以使用 debugPrint:

let headers: HTTPHeaders = ["Accept": "application/json"]

//In the empty quotes, enter you API url info.
let request = Alamofire.request("", headers: headers)
    .responseJSON { response in 
        // ...
    }
debugPrint(request)

从那里开始,您就可以创建 POST 调用了。

关于ios - swift ios 使用 alamofire 将 curl 转换为 swift curl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49745030/

相关文章:

javascript - 检测 Chrome for iOS 地址栏何时显示

ios - Ios App如何从后台转到前台

ios - 如何调用func渲染器(_ :didAdd:for:)

ios - iPhone 中的蓝牙编程

android - 将 TypeScript 与 HTML5 iOS 应用程序的专有属性结合使用

objective-c - 当用户单击 View 的背景时,如何使键盘消失?

json - Swift JSON 持续时间

java - WSO2 DSS 错误 : javax. xml.stream.XMLStreamException:无效的凝视元素

javascript - 如何通过 PHP 搜索 Linkedin?

batch-file - 将 curl 命令输出存储在批处理脚本的变量中