Search code examples
jsonswiftswift3alamofire

Taking the response of JSON and showing it in a textField


This function will upload a photo to a bucket and then show a direct link to that photo in a text field. What I wanted to do is to shorten the link, so I created a post request to Google's URL shortener using alamofire, and it worked, but I'm I don't know how to show it in a textfield.

Here is the function

func ImageDownloader(){


    UIApplication.shared.isNetworkActivityIndicatorVisible = true

    let imageContained = viewimage.image

    let storage = Storage.storage()
    var storageRef = storage.reference()
    storageRef = storage.reference(forURL: "") // Link to bucket

    var data = NSData()
    data = UIImageJPEGRepresentation(imageContained!, 0.8)! as NSData
    let dateFormat = DateFormatter()
    dateFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let imageName = dateFormat.string(from: NSDate() as Date)
    let imagePath = "images/\(imageName).jpg"
    let metaData = StorageMetadata()
    let mountainsRef = storageRef.child(imagePath).putData(data as Data, metadata: metaData){(metaData,error) in
        if let error = error {
            print(error.localizedDescription)
            return
        }else{
            //store downloadURL
            let downloadURL = metaData!.downloadURL()!.absoluteString
            self.getLink.text = downloadURL



                struct dlink {
                    let longLink: String
                }
                let v = dlink(longLink: "\(downloadURL)")

                let parameters = ["longUrl":"\(v.longLink)","MYURL":""]

                Alamofire.request("https://www.googleapis.com/urlshortener/v1/url?key=MY_KEY", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
                    print(response)
                }


            }
        metaData?.contentType = "image/jpeg"
        }

and here is the JSON response showing that it works fine.

enter image description here

Any kind of help would be appreciated!


Solution

  • You need to access the result.value of response to get your serialized JSON response.

    Alamofire.request("https://www.googleapis.com/urlshortener/v1/url?key=MY_KEY", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
         if let dictionary = response.result.value as? [String:Any] {
             //Now subscript on dictionary with keys to get your values.
             let id = dictionary["id"] as? String ?? "DefaultValue" //set default value that you want
             let kind = dictionary["kind"] as? String ?? "DV"
             let longUrl = dictionary["longUrl"] as? String ?? "DV"
             print(id, kind, longUrl)
         }
    }
    

    You can check Response Handling section of Alamofire docs to get more idea.