Skip to content

Instantly share code, notes, and snippets.

@CrowMagic
Last active July 25, 2018 09:46
Show Gist options
  • Save CrowMagic/c797ee077e204bfca4031895a254ef1d to your computer and use it in GitHub Desktop.
Save CrowMagic/c797ee077e204bfca4031895a254ef1d to your computer and use it in GitHub Desktop.
Base64URL
//
// Base64URLUtils.swift
// CodeRepo
//
// Created by tramp on 23/04/2018.
// Copyright © 2018 tramp. All rights reserved.
//
import Foundation
/// 转换urlBase64编码的字符串为base64编码的字符串
///
/// - Parameter base64URL: urlBase64编码的字符串
/// - Returns: base64编码的字符串
func convertBase64URLToBase64(_ base64URL: String) -> String {
var result = base64URL
.then(from: "-", to: "+")
.then(from: "_", to: "/")
.then(from: "\n", to: "")
.then(from: "\r", to: "")
var equalsToBeAdded = base64URL.count % 4
/// 根据base64编码规则,末尾的=只有0, 1,2三种可能
if equalsToBeAdded > 0 {
if equalsToBeAdded == 3 {
equalsToBeAdded = 1
}
(0..<equalsToBeAdded).forEach{ _ in result.append("=")}
}
return result
}
/// 转换base64编码的字符串为urlBase64编码的字符串
///
/// - Parameter base64: base64编码的字符串
/// - Returns: urlBase64编码的字符串
func convertBase64ToBase64URL(_ base64: String) -> String {
let result = base64
.then(from: "+", to: "-")
.then(from: "/", to: "_")
.then(from: "=", to: "")
return result
}
extension String {
func then(from: String, to: String) -> String {
return self.replacingOccurrences(of: from, with: to, options: .literal, range: range(of: self))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment