http - 从 Swift 2.2 使用 Freshdesk API

标签 http swift2 freshdesk

我正在尝试使用 Swift 2.2 程序 ( Here's the API ) 中的 API 从 FreshDesk 检索所有票证

以下 curl 有效:

curl -v -u myEmail@example.com:myPassword -X GET 'https://mydomain.freshdesk.com/api/v2/tickets'

我已经创建了这个函数来检索门票:

func getAllTickets() {
    let username = "myEmail@example.com"
    let password = "myPassword"

    let loginString = "\(username):\(password)"
    let loginData = loginString.data(using: .utf8)
    let base64LoginString = loginData?.base64EncodedString(options: [])

    if let url = NSURL(string: "https://mydomain.freshdesk.com/api/v2/tickets"){
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "GET"
        request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

        let session = URLSession.shared
        session.dataTask(with: request as URLRequest, completionHandler: { (returnData, response, error) -> Void in
            if let error = error {
                // couldn't even make the call - probably no network...
                // maybe save it in the DB for next time?
                print("Error connecting to Freshdesk API - error is: \(error.localizedDescription)")

                if error.localizedDescription == "The Internet connection appears to be offline" {
                    // TODO - save error up until next time
                }
                return
            }
            let strData = NSString(data: returnData!, encoding: String.Encoding.utf8.rawValue)
            print("GOT RESULT: \(strData)")
        }).resume()
    }
}

我得到的输出是: 获得结果:可选({“code”:“invalid_credentials”,“message”:“您必须登录才能执行此操作。”})

但鉴于 curl 有效,我确定用户名/密码是正确的

最佳答案

this answer 的帮助下,我在没有 Alamofire 的情况下也能正常工作

下面是Swift 3

如何检索票证

func getAllTickets() {
    let user = "yourFreshDeskEmail.example.com"
    let password = "yourFreshDeskPassword"

    let credentialData = "\(user):\(password)".data(using: String.Encoding.utf8)!
    let base64Credentials = credentialData.base64EncodedString(options: [])

    if let url = NSURL(string: "https://yourdomainname.freshdesk.com/api/v2/tickets"){
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "GET"

        request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")

        let session = URLSession.shared
        session.dataTask(with: request as URLRequest, completionHandler: { (returnData, response, error) -> Void in
            if let error = error {

                print("Error connecting to Freshdesk API - error is: \(error.localizedDescription)")

                if error.localizedDescription == "The Internet connection appears to be offline" {
                    // Handle error
                }
                return
            }
            let strData = NSString(data: returnData!, encoding: String.Encoding.utf8.rawValue)
            print("GOT RESULT: \(strData)")
        }).resume()
    }
}

如何张贴工单

func raiseFreshdeskTicket(description: String,
                          subject: String,
                          usersEmail: String,
                          priority: Int,
                          status: Int,
                          ccEmails: [String],
                          type: String ) {
    let json = [ "description" : description, "subject" : subject, "email" : usersEmail,"priority" : priority, "status" : status, "cc_emails" : ccEmails, "type": type ] as [String : Any]

    do {

        let user = "yourFreshDeskEmail.example.com"
        let password = "yourFreshDeskPassword"

        let credentialData = "\(user):\(password)".data(using: String.Encoding.utf8)!
        let base64Credentials = credentialData.base64EncodedString(options: [])

        let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)

        // create post request
        let url = NSURL(string: "https://yourdomainname.freshdesk.com/api/v2/tickets")!
        let request = NSMutableURLRequest(url: url as URL)

        request.httpMethod = "POST"

        // insert json data to the request
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")
        request.httpBody = jsonData


        let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
            if error != nil{
                print("Error -> \(error)")
                return
            }

            do {
                let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]

                print("Result -> \(result)")

            } catch {
                print("Error -> \(error)")
            }
        }

        task.resume()
        // return task



    } catch {
        print(error)
    }
}

关于http - 从 Swift 2.2 使用 Freshdesk API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39509115/

相关文章:

javascript - 将数据从 HTTPS 页面发送到本地主机服务器

http - Flutter http 客户端给出 FormatException : Unexpected character (at character 1) <! DOCTYPE html>

javascript - 预填充字段 - WordPress 平台上的 Freshdesk

javascript - Freshdesk - 超时后初始化

java - 如何获取 FileChannel.transferFrom 在写入过程中写入的字节数

http - 读取缓冲区并将其重写为 Go 中的 http.Response

swift - CFArray takeRetainedValue() 删除导致崩溃

ios - 如何在 Swift 2.0 中创建一个 dispatch_block_t 数组?

ios - 找到 2 个 NSIndexPath 数组的交集

android - 在 android 中集成 Freshdesk 时文件提供程序异常