iosswiftgoogle-url-shortener

Using Alamofire to get short URL from Google with Swift


I'm trying to add short url in my app as a tool for the users and this is what a came with from this answer and unfortunately it didn't work! :

import AFNetworking

let googleShortURLKey = "MYKEY"

func getShortURLFromGoogle(longURL: String) {
    let manager = AFHTTPSessionManager()
    manager.requestSerializer = AFJSONRequestSerializer() as AFJSONRequestSerializer
    let params = [ "longUrl": longURL ]

    manager.POST("https://www.googleapis.com/urlshortener/v1/url?key=\(googleShortURLKey)", parameters: params, success: {
        (operation: AFHTTPRequestSerializer!,responseObject: AnyObject!) in
        if let responseObject = responseObject as? NSDictionary {
            self.shortURL = responseObject["id"] as? String //That's what you want
        }
    },
                 failure: { (operation: AFHTTPRequestSerializer!,error: NSError!) in
                    print("Error while requesting shortened: " + error.localizedDescription)
    })
}

Solution

  • I have solve your question using Alamofire framework :

    import UIKit
    import Alamofire
    
    
    class ShortURLToolViewController: UIViewController {
    
    
        let googleShortURLApiWithKey = "https://www.googleapis.com/urlshortener/v1/url?key=YOURKEY"
        var finalShortURL: String? // To save the short url
    
        override func viewDidLoad() {
            super.viewDidLoad()
            getShortURLFromGoogle(longURL: "https://github.com/")
        }
    
        func getShortURLFromGoogle (longURL: String){
            let params = ["longUrl": longURL]
    
            Alamofire.request(googleShortURLApiWithKey, method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON { responds in
    
                if let JSON = responds.result.value {
                    print(JSON)
                    let json = try? JSONSerialization.jsonObject(with: responds.data!, options: [])
                    if let dictionary = json as? [String: Any] {
                        if let shortURL = dictionary["id"] as? String {
                            // access individual value in dictionary
                            self.finalShortURL = shortURL
                            print(self.finalShortURL ?? "NO DATA!")
                        }
                    }
                }
            }
        }
    
    }//Class Ends