LoginSignup
5
6

More than 5 years have passed since last update.

Swiftでgoo.glの短縮URLを生成するやり方

Last updated at Posted at 2016-05-06

開発環境

ElCaption 10.11.4
Swift2.2
Xcode7.3

事前準備

APIキーを取得する必要があるのですがPHPで短縮URLを作成する方法まとめ(全7サイト)に取得方法が書いてあるのでここでは割愛します。

コード

SwiftでHTTPリクエストするの記事を参考にコードを作成しました。
ここでは、緯度経度を指定したGoogleMapのURLをサンプルとして利用しています。
(取得したAPIキーを書き換えるのを忘れずに!)

ViewController
class ViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()

        postAsync()

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    // HTTP-POST
    func postAsync() {

        let apiKey = "APIキーをここに入力してください"
        // create the url-request

        //アプリごとにキーは生成しないといけない
        let urlString = "https://www.googleapis.com/urlshortener/v1/url?key=" + apiKey
        let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)

        // set the method(HTTP-POST)
        request.HTTPMethod = "POST"
        // set the header(s)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        // set the request-body(JSON)
        let params: [String: AnyObject] = [
            "longUrl":"http://maps.google.com/maps?q=35,139&ll=35,139"
        ]

        do {
            request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.init(rawValue: 2))
        } catch {
            // Error Handling
            print("NSJSONSerialization Error")
            return
        }


        // use NSURLSessionDataTask
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error in
            if (error == nil) {
                let result = NSString(data: data!, encoding: NSUTF8StringEncoding)!
                print(result)
            } else {
                print(error)
            }
        })
        task.resume()

    }


}

結果

idを指定してあげれば、短縮URLが取得できます。

{
 "kind": "urlshortener#url",
 "id": "http://goo.gl/rV3xdk",
 "longUrl": "http://maps.google.com/maps?q=35,139&ll=35,139"
}
5
6
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
5
6