58
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftでURLエンコードする

Last updated at Posted at 2014-07-03

※追記コメントで知りました。iOS7以降なら下記もOKとのことシンプル!

iOS7以降OK

let encodedString = targetString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
let decodedString = encodedString.stringByRemovingPercentEncoding;

iOS7未満対応?

APIに日本語を投げ込むときなどこんな感じで。
デフォルトの関数で用意して欲しい…。

extension String {
    
    func escapeStr() -> String {
        var raw: NSString = self
        var str = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,raw,"[].",":/?&=;+!@#$()',*",CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
        return str
    }
}

class ViewController: UIViewController { 
    
    let defaultRadius = 300
    
    @IBOutlet var searchBar: UISearchBar
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        var query = searchBar.text
        var encoded = query.escapeStr()
    }
    
}
58
55
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
58
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?