Http 使用Swift 2.2中的Freshdesk API

Http 使用Swift 2.2中的Freshdesk API,http,swift2,freshdesk,Http,Swift2,Freshdesk,我正在尝试使用Swift 2.2程序()的API从FreshDesk检索所有票证 以下方法有效: 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 = "myPa

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

以下方法有效:

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()
    }
}
我得到的结果是: 获取结果:可选({“代码”:“无效的\u凭证”,“消息”:“您必须登录才能执行此操作”


但是我确信用户名/密码是正确的,因为curl是有效的

好的,我自己想好了,以防万一其他人也这么做。。。 我在用Alamofire建立网络。这是Alamofire(3.4)的一个稍微旧的版本,因为cocoapods认为这是OSX的最新版本。因此,如果使用4.x,您可能需要稍微更新Alamofire调用,但这并不难

请注意,使用Alamofire身份验证对我不起作用,这就是我自己构建base64Credentials的原因

下面介绍如何检索票证

func retrieveFreshdeskTickets() {

    let user = "yourFreshDeskEmail@whatever.com"
    let password = "yourFreshDeskPassword"
    let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
    let base64Credentials = credentialData.base64EncodedStringWithOptions([])
    let headers = ["Authorization": "Basic \(base64Credentials)"]

    let freshDeskEndPoint: String = "https://yourDomainName.freshdesk.com/api/v2/tickets"

    Alamofire.request(.GET, freshDeskEndPoint, headers: headers)
        .responseJSON { response in
            guard response.result.error == nil else {
                print("error retrieving freshdesk tickets")
                print(response.result.error!)
                return
            }

            if let value = response.result.value {
                // print the tickets
                print(value)
            }
    }
}
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 user = "yourFreshDeskEmail@whatever.com"
    let password = "yourFreshDeskPassword"
    let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
    let base64Credentials = credentialData.base64EncodedStringWithOptions([])
    let headers = ["Authorization": "Basic \(base64Credentials)"]

    let parameters = [
        "description": description,
        "subject": subject,
        "email": usersEmail,
        "priority": priority ,
        "status": status,
        "cc_emails": ccEmails,
        "type": type
        ] as [String : AnyObject]

    let freshDeskEndPoint: String = "https://yourDomainName.freshdesk.com/api/v2/tickets"

    Alamofire.request(.POST, freshDeskEndPoint, headers: headers, parameters: parameters, encoding: .JSON)
        .responseJSON { response in
            guard response.result.error == nil else {
                print("error calling adding freshdesk ticket")
                print(response.result.error!)
                return
            }
            if let value = response.result.value {
                print(value)
            }
    }

}
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)
    }
}
下面是一个调用post函数的示例

let errorDescription = "Log from program - this is what went wrong"
raiseFreshdeskTicket(errorDescription, subject: "Automated Error report from <your program name>", usersEmail: "yourAppUser@zing.com", priority: 1, status: 2, ccEmails: [], type: "Problem")
let errorDescription=“从程序记录-这就是出错的原因”
raiseFreshdeskTicket(错误描述,主题:“来自的自动错误报告”,UsersMail:yourAppUser@zing.com,优先级:1,状态:2,电子邮件:[],键入:“问题”)

我还可以在没有Alamofire的情况下使用它,并得到了来自

以下是Swift 3

如何检索票证

func retrieveFreshdeskTickets() {

    let user = "yourFreshDeskEmail@whatever.com"
    let password = "yourFreshDeskPassword"
    let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
    let base64Credentials = credentialData.base64EncodedStringWithOptions([])
    let headers = ["Authorization": "Basic \(base64Credentials)"]

    let freshDeskEndPoint: String = "https://yourDomainName.freshdesk.com/api/v2/tickets"

    Alamofire.request(.GET, freshDeskEndPoint, headers: headers)
        .responseJSON { response in
            guard response.result.error == nil else {
                print("error retrieving freshdesk tickets")
                print(response.result.error!)
                return
            }

            if let value = response.result.value {
                // print the tickets
                print(value)
            }
    }
}
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 user = "yourFreshDeskEmail@whatever.com"
    let password = "yourFreshDeskPassword"
    let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
    let base64Credentials = credentialData.base64EncodedStringWithOptions([])
    let headers = ["Authorization": "Basic \(base64Credentials)"]

    let parameters = [
        "description": description,
        "subject": subject,
        "email": usersEmail,
        "priority": priority ,
        "status": status,
        "cc_emails": ccEmails,
        "type": type
        ] as [String : AnyObject]

    let freshDeskEndPoint: String = "https://yourDomainName.freshdesk.com/api/v2/tickets"

    Alamofire.request(.POST, freshDeskEndPoint, headers: headers, parameters: parameters, encoding: .JSON)
        .responseJSON { response in
            guard response.result.error == nil else {
                print("error calling adding freshdesk ticket")
                print(response.result.error!)
                return
            }
            if let value = response.result.value {
                print(value)
            }
    }

}
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)
    }
}