Skip to content

Instantly share code, notes, and snippets.

@hishma
Created October 23, 2019 16:02

Revisions

  1. hishma created this gist Oct 23, 2019.
    27 changes: 27 additions & 0 deletions String+RFC3986.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    import Foundation

    extension String {
    public func addingPercentEncodingForRFC3986() -> String? {
    let unreserved = "-._~/?"
    let allowed = NSMutableCharacterSet.alphanumeric()
    allowed.addCharacters(in: unreserved)
    return self.addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)
    }

    public func addingPercentEncodingForFormData(plusForSpace: Bool=false) -> String? {
    let unreserved = "*-._"
    let allowed = NSMutableCharacterSet.alphanumeric()
    allowed.addCharacters(in: unreserved)

    if plusForSpace {
    allowed.addCharacters(in: " ")
    }

    var encoded = self.addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)

    if plusForSpace {
    encoded = encoded?.replacingOccurrences(of: " ", with: "+")
    }
    return encoded
    }
    }