LoginSignup
1
2

More than 5 years have passed since last update.

NSURLを短縮URLにする拡張

Last updated at Posted at 2015-10-23

エラーハンドリングしてないのでもうちょいちゃんと書かないといけない。
googleの短縮URLのAPIKeyを入れれば使えます。
因みに認証用のURLとかってgoogleの短縮URLだと短縮できないんですね…。


extension String {
    func shortURL(success:(shortedUrl:NSURL)->()){
        let apiKey = "AIzaSyBLOTjWpximy4FF9q0V-hKoaqjlo2KNwi4"
        let url    = "https://www.googleapis.com/urlshortener/v1/url?key="
        let request = NSMutableURLRequest(URL: NSURL(string: url+apiKey)!, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 10.0)
        request.HTTPMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.HTTPBody = "{\"longUrl\": \"\(self)\"}".dataUsingEncoding(NSUTF8StringEncoding)
        let session = NSURLSession.sharedSession()
        session.dataTaskWithRequest(request) { (data, response, error) -> Void in
            if error != nil {
                print(error?.localizedDescription)
            }else{
                print(String(data: data!, encoding: NSUTF8StringEncoding))
                let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
                if let status = json as? Dictionary<String,String>{
                    success(shorted: status["id"]!)
                }
            }
            }.resume()
    }
}

使い方

url.shortURL({ (shortedUrl) -> () in
    print(shortedUrl)
})

Stringにしたけど、NSURLでもいいかもね

1
2
0

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
1
2