簡體   English   中英

在 swift 中使用 twilio 進行電話號碼驗證時出錯

[英]Error while doing phone number verification using twilio in swift

我想通過獲取一次性密碼來驗證電話號碼。 但是我收到了一些錯誤。 請查看下面的代碼並幫助我解決它。 我正在使用 Twilio 進行移動驗證。 和 Alamofire API 請求。 但是我得到的錯誤是:-

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

我的代碼是:-

這是我的 model class:-

...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"

Twilio 開發者布道師在這里。

看起來您的代碼似乎正在嘗試直接從設備調用 Twilio API 並且您沒有在其中設置您的帳戶 SID 或身份驗證令牌。

這里的問題是你不應該在你的應用程序中存儲或訪問你的授權令牌。 這將使您的帳戶 sid 和 auth 令牌容易被盜,然后被用來濫用您的帳戶。

相反,您應該創建一個與 Twilio API 對話的服務器端應用程序,然后從您的應用程序調用它。

正如 Jamil 指出的那樣,您可以在 iOS 中使用 Twilio 驗證和 Swift 執行電話驗證,我建議您通過該博客帖子 go。 它包括一個示例服務器端應用程序,用於調用 Twilio 驗證 API內置於 Python,但您也可以構建自己的應用程序。

這是示例代碼:

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

有關更多信息,請查看此鏈接: 鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM