快速使用twilio进行电话号码验证时出错

时间:2020-02-24 05:04:02

标签: swift twilio alamofire

我想通过获取一次密码来验证电话号码。但是我遇到了一些错误。请查看下面的代码,并帮助我解决该问题。我正在使用Twilio进行移动验证。和Alamofire进行API请求。但是我得到的错误是:-

Authentication Error - No credentials provided.
The data couldn’t be read because it isn’t in the correct format

我的代码是:-

这是我的模型课:-

...struct SendVerificationCode: Codable {
let status: String?
let payee: String?
let dateUpdated: Date?
let sendCodeAttempts: [SendCodeAttempt]?
let accountSid, to: String?
let amount: Int?
let valid: Bool?
let lookup: Lookup?
let url: String?
let sid: String?
let dateCreated: Date?
let serviceSid, channel: String?

enum CodingKeys: String, CodingKey {
    case status, payee
    case dateUpdated = "date_updated"
    case sendCodeAttempts = "send_code_attempts"
    case accountSid = "account_sid"
    case to, amount, valid, lookup, url, sid
    case dateCreated = "date_created"
    case serviceSid = "service_sid"
    case channel
}
}


struct Lookup: Codable {
let carrier: Carrier?
}


struct Carrier: Codable {
let mobileCountryCode, type: String?
let errorCode: String?
let mobileNetworkCode, name: String?

enum CodingKeys: String, CodingKey {
    case mobileCountryCode = "mobile_country_code"
    case type
    case errorCode = "error_code"
    case mobileNetworkCode = "mobile_network_code"
    case name
}
}


 struct SendCodeAttempt: Codable {
let channel, time: String?
}...

Api请求:-

...func sendcode(mobileWithCode: String, completion: @escaping sendTwillioVerificationCodeCompletion) {

    let url = URL(string: SEND_TWILIO_VERIFICATION_CODE)
   var urlRequest = URLRequest(url: url!)
   urlRequest.httpMethod = HTTPMethod.post.rawValue
   urlRequest.addValue(userNameData, forHTTPHeaderField: "Username")
    urlRequest.addValue(PasswordData, forHTTPHeaderField: "Password")
    urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")


   Alamofire.request(urlRequest).responseJSON { (response) in
       if let error = response.result.error {
           debugPrint(error.localizedDescription)
           completion(nil)
           return
       }

       guard let data = response.data else { return completion(nil)}

       Common.sharedInstance().printRequestOutput(data: data)

       let jsonDecoder = JSONDecoder()
       do {
           let clear = try jsonDecoder.decode(SendVerificationCode.self, from: data)
           completion(clear)
       } catch {
           debugPrint(error.localizedDescription)
           completion(nil)
       }
   }
}...

但是我遇到了错误:-

   {"code": 20003, "detail": "Your AccountSid or AuthToken was incorrect.", "message": "Authentication Error - No credentials provided", "more_info": "https://www.twilio.com/docs/errors/20003", "status": 401}
   "The data couldn’t be read because it isn’t in the correct format."

我还尝试了以下代码:-

import Foundation
semaphore = DispatchSemaphore (value: 0)

let parameters = "To=+919778882332&Channel=sms"
let postData =  parameters.data(using: .utf8)

var request = URLRequest(url: URL(string:  myUrl)!,timeoutInterval: Double.infinity)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue(requestData, forHTTPHeaderField: "Authorization")

request.httpMethod = "POST"
request.httpBody = postData

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
guard let data = data else {
print(String(describing: error))
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()
}

task.resume()
semaphore.wait()

但是我遇到了类似的错误

"Invalid parameter"

2 个答案:

答案 0 :(得分:2)

这里是Twilio开发人员的传播者。

似乎您的代码正试图直接从设备调用Twilio API,并且您并未在其中设置帐户SID或Auth令牌。

这里的问题是,您不应在应用程序内存储或访问身份验证令牌。这会使您的帐户sid和auth令牌易于被盗,然后被用来滥用您的帐户。

相反,您应该创建一个与Twilio API对话的服务器端应用程序,然后从您的应用程序中调用它。

正如贾米尔(Jamil)指出的那样,您可以在performing phone verification in iOS with Twilio Verify and Swift上关注一篇博客文章,我建议您仔细阅读。它包括用Python内置的an example server side application to call the Twilio Verify API,但您也可以自己构建。

答案 1 :(得分:1)

这是示例代码:

import UIKit

class ViewController: UIViewController {

    static let path = Bundle.main.path(forResource: "Config", ofType: "plist")
    static let config = NSDictionary(contentsOfFile: path!)
    private static let baseURLString = config!["serverUrl"] as! String

    @IBOutlet var countryCodeField: UITextField! = UITextField()
    @IBOutlet var phoneNumberField: UITextField! = UITextField()
    @IBAction func sendVerification() {
        if let phoneNumber = phoneNumberField.text,
            let countryCode = countryCodeField.text {
            ViewController.sendVerificationCode(countryCode, phoneNumber)
        }
    }

    static func sendVerificationCode(_ countryCode: String, _ phoneNumber: String) {

        let parameters = [
            "via": "sms",
            "country_code": countryCode,
            "phone_number": phoneNumber
        ]

        let path = "start"
        let method = "POST"

        let urlPath = "\(baseURLString)/\(path)"
        var components = URLComponents(string: urlPath)!

        var queryItems = [URLQueryItem]()

        for (key, value) in parameters {
            let item = URLQueryItem(name: key, value: value)
            queryItems.append(item)
        }

        components.queryItems = queryItems

        let url = components.url!

        var request = URLRequest(url: url)
        request.httpMethod = method

        let session: URLSession = {
            let config = URLSessionConfiguration.default
            return URLSession(configuration: config)
        }()

        let task = session.dataTask(with: request) {
            (data, response, error) in
            if let data = data {
                do {
                    let jsonSerialized = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]

                    print(jsonSerialized!)
                }  catch let error as NSError {
                    print(error.localizedDescription)
                }
            } else if let error = error {
                print(error.localizedDescription)
            }
        }
        task.resume()
    }
}

有关更多信息,请检查以下链接:Link

相关问题