Method to return value retrieved from HTTP request [duplicate]





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0
















This question already has an answer here:




  • Returning data from async call in Swift function

    10 answers




I have a method which performs an HTTP request and retrieves data from a website, it's working as expected, I'm getting the data correctly. What I haven't been able to do is return the retrieved value when the method is called.



Here is the code...



func myFunction(zipCode: String)->String{
var myData:String = ""

let siteLink = "http://example.com/zip/" + zipCode
let url = URL(string: siteLink)

let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard error == nil else {
print(error!)
return
}
guard let data = data else {
print("Data is empty")
return
}
let json = try! JSONSerialization.jsonObject(with: data, options: )
guard let jsonArray = json as? [[String: String]] else {
return
}
myData = jsonArray[0]["MyPropertyName"]!
// Here, myData outputs, "Info for zip code 52484 from HTTP request"
}

task.resume()

return myData
}


When I call myFunction I get and empty string...



myFunction(zipCode: "52484")// Outputs an empty string


What I was expecting to see is a return value of "Info for zip code 52484 from HTTP request" since the myData variable was modified inside the let task = before the return call. I tried returning inside the let task = but this cannot be done in Swift.



How can I return the retrieved value when the myFunction is called?










share|improve this question













marked as duplicate by Dávid Pásztor swift
Users with the  swift badge can single-handedly close swift questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 23 '18 at 15:42


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

























    0
















    This question already has an answer here:




    • Returning data from async call in Swift function

      10 answers




    I have a method which performs an HTTP request and retrieves data from a website, it's working as expected, I'm getting the data correctly. What I haven't been able to do is return the retrieved value when the method is called.



    Here is the code...



    func myFunction(zipCode: String)->String{
    var myData:String = ""

    let siteLink = "http://example.com/zip/" + zipCode
    let url = URL(string: siteLink)

    let task = URLSession.shared.dataTask(with: url!) { data, response, error in
    guard error == nil else {
    print(error!)
    return
    }
    guard let data = data else {
    print("Data is empty")
    return
    }
    let json = try! JSONSerialization.jsonObject(with: data, options: )
    guard let jsonArray = json as? [[String: String]] else {
    return
    }
    myData = jsonArray[0]["MyPropertyName"]!
    // Here, myData outputs, "Info for zip code 52484 from HTTP request"
    }

    task.resume()

    return myData
    }


    When I call myFunction I get and empty string...



    myFunction(zipCode: "52484")// Outputs an empty string


    What I was expecting to see is a return value of "Info for zip code 52484 from HTTP request" since the myData variable was modified inside the let task = before the return call. I tried returning inside the let task = but this cannot be done in Swift.



    How can I return the retrieved value when the myFunction is called?










    share|improve this question













    marked as duplicate by Dávid Pásztor swift
    Users with the  swift badge can single-handedly close swift questions as duplicates and reopen them as needed.

    StackExchange.ready(function() {
    if (StackExchange.options.isMobile) return;

    $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
    var $hover = $(this).addClass('hover-bound'),
    $msg = $hover.siblings('.dupe-hammer-message');

    $hover.hover(
    function() {
    $hover.showInfoMessage('', {
    messageElement: $msg.clone().show(),
    transient: false,
    position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
    dismissable: false,
    relativeToBody: true
    });
    },
    function() {
    StackExchange.helpers.removeMessages();
    }
    );
    });
    });
    Nov 23 '18 at 15:42


    This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





















      0












      0








      0









      This question already has an answer here:




      • Returning data from async call in Swift function

        10 answers




      I have a method which performs an HTTP request and retrieves data from a website, it's working as expected, I'm getting the data correctly. What I haven't been able to do is return the retrieved value when the method is called.



      Here is the code...



      func myFunction(zipCode: String)->String{
      var myData:String = ""

      let siteLink = "http://example.com/zip/" + zipCode
      let url = URL(string: siteLink)

      let task = URLSession.shared.dataTask(with: url!) { data, response, error in
      guard error == nil else {
      print(error!)
      return
      }
      guard let data = data else {
      print("Data is empty")
      return
      }
      let json = try! JSONSerialization.jsonObject(with: data, options: )
      guard let jsonArray = json as? [[String: String]] else {
      return
      }
      myData = jsonArray[0]["MyPropertyName"]!
      // Here, myData outputs, "Info for zip code 52484 from HTTP request"
      }

      task.resume()

      return myData
      }


      When I call myFunction I get and empty string...



      myFunction(zipCode: "52484")// Outputs an empty string


      What I was expecting to see is a return value of "Info for zip code 52484 from HTTP request" since the myData variable was modified inside the let task = before the return call. I tried returning inside the let task = but this cannot be done in Swift.



      How can I return the retrieved value when the myFunction is called?










      share|improve this question















      This question already has an answer here:




      • Returning data from async call in Swift function

        10 answers




      I have a method which performs an HTTP request and retrieves data from a website, it's working as expected, I'm getting the data correctly. What I haven't been able to do is return the retrieved value when the method is called.



      Here is the code...



      func myFunction(zipCode: String)->String{
      var myData:String = ""

      let siteLink = "http://example.com/zip/" + zipCode
      let url = URL(string: siteLink)

      let task = URLSession.shared.dataTask(with: url!) { data, response, error in
      guard error == nil else {
      print(error!)
      return
      }
      guard let data = data else {
      print("Data is empty")
      return
      }
      let json = try! JSONSerialization.jsonObject(with: data, options: )
      guard let jsonArray = json as? [[String: String]] else {
      return
      }
      myData = jsonArray[0]["MyPropertyName"]!
      // Here, myData outputs, "Info for zip code 52484 from HTTP request"
      }

      task.resume()

      return myData
      }


      When I call myFunction I get and empty string...



      myFunction(zipCode: "52484")// Outputs an empty string


      What I was expecting to see is a return value of "Info for zip code 52484 from HTTP request" since the myData variable was modified inside the let task = before the return call. I tried returning inside the let task = but this cannot be done in Swift.



      How can I return the retrieved value when the myFunction is called?





      This question already has an answer here:




      • Returning data from async call in Swift function

        10 answers








      swift return return-value nsurlsession






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 23 '18 at 14:07









      fs_tigrefs_tigre

      4,76974177




      4,76974177




      marked as duplicate by Dávid Pásztor swift
      Users with the  swift badge can single-handedly close swift questions as duplicates and reopen them as needed.

      StackExchange.ready(function() {
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function() {
      $hover.showInfoMessage('', {
      messageElement: $msg.clone().show(),
      transient: false,
      position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
      dismissable: false,
      relativeToBody: true
      });
      },
      function() {
      StackExchange.helpers.removeMessages();
      }
      );
      });
      });
      Nov 23 '18 at 15:42


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









      marked as duplicate by Dávid Pásztor swift
      Users with the  swift badge can single-handedly close swift questions as duplicates and reopen them as needed.

      StackExchange.ready(function() {
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function() {
      $hover.showInfoMessage('', {
      messageElement: $msg.clone().show(),
      transient: false,
      position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
      dismissable: false,
      relativeToBody: true
      });
      },
      function() {
      StackExchange.helpers.removeMessages();
      }
      );
      });
      });
      Nov 23 '18 at 15:42


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


























          1 Answer
          1






          active

          oldest

          votes


















          1














          You need a completion as request is asynchronous



          func myFunction(zipCode: String,completion:@escaping(_ str:String?) -> () ) {

          let siteLink = "http://example.com/zip/" + zipCode
          let url = URL(string: siteLink)

          let task = URLSession.shared.dataTask(with: url!) { data, response, error in
          guard error == nil else {
          print(error!)
          completion(nil)
          return
          }
          guard let data = data else {
          print("Data is empty")
          completion(nil)
          return
          }
          let json = try! JSONSerialization.jsonObject(with: data, options: )
          guard let jsonArray = json as? [[String: String]] else {
          completion(nil)
          return
          }
          let myData = jsonArray[0]["MyPropertyName"]!
          completion(myData)
          }
          task.resume()
          }




          Call



          myFunction(zipCode: "52484") { (str) in 
          if let st = str {
          print(st)
          }
          }





          share|improve this answer






























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You need a completion as request is asynchronous



            func myFunction(zipCode: String,completion:@escaping(_ str:String?) -> () ) {

            let siteLink = "http://example.com/zip/" + zipCode
            let url = URL(string: siteLink)

            let task = URLSession.shared.dataTask(with: url!) { data, response, error in
            guard error == nil else {
            print(error!)
            completion(nil)
            return
            }
            guard let data = data else {
            print("Data is empty")
            completion(nil)
            return
            }
            let json = try! JSONSerialization.jsonObject(with: data, options: )
            guard let jsonArray = json as? [[String: String]] else {
            completion(nil)
            return
            }
            let myData = jsonArray[0]["MyPropertyName"]!
            completion(myData)
            }
            task.resume()
            }




            Call



            myFunction(zipCode: "52484") { (str) in 
            if let st = str {
            print(st)
            }
            }





            share|improve this answer




























              1














              You need a completion as request is asynchronous



              func myFunction(zipCode: String,completion:@escaping(_ str:String?) -> () ) {

              let siteLink = "http://example.com/zip/" + zipCode
              let url = URL(string: siteLink)

              let task = URLSession.shared.dataTask(with: url!) { data, response, error in
              guard error == nil else {
              print(error!)
              completion(nil)
              return
              }
              guard let data = data else {
              print("Data is empty")
              completion(nil)
              return
              }
              let json = try! JSONSerialization.jsonObject(with: data, options: )
              guard let jsonArray = json as? [[String: String]] else {
              completion(nil)
              return
              }
              let myData = jsonArray[0]["MyPropertyName"]!
              completion(myData)
              }
              task.resume()
              }




              Call



              myFunction(zipCode: "52484") { (str) in 
              if let st = str {
              print(st)
              }
              }





              share|improve this answer


























                1












                1








                1







                You need a completion as request is asynchronous



                func myFunction(zipCode: String,completion:@escaping(_ str:String?) -> () ) {

                let siteLink = "http://example.com/zip/" + zipCode
                let url = URL(string: siteLink)

                let task = URLSession.shared.dataTask(with: url!) { data, response, error in
                guard error == nil else {
                print(error!)
                completion(nil)
                return
                }
                guard let data = data else {
                print("Data is empty")
                completion(nil)
                return
                }
                let json = try! JSONSerialization.jsonObject(with: data, options: )
                guard let jsonArray = json as? [[String: String]] else {
                completion(nil)
                return
                }
                let myData = jsonArray[0]["MyPropertyName"]!
                completion(myData)
                }
                task.resume()
                }




                Call



                myFunction(zipCode: "52484") { (str) in 
                if let st = str {
                print(st)
                }
                }





                share|improve this answer













                You need a completion as request is asynchronous



                func myFunction(zipCode: String,completion:@escaping(_ str:String?) -> () ) {

                let siteLink = "http://example.com/zip/" + zipCode
                let url = URL(string: siteLink)

                let task = URLSession.shared.dataTask(with: url!) { data, response, error in
                guard error == nil else {
                print(error!)
                completion(nil)
                return
                }
                guard let data = data else {
                print("Data is empty")
                completion(nil)
                return
                }
                let json = try! JSONSerialization.jsonObject(with: data, options: )
                guard let jsonArray = json as? [[String: String]] else {
                completion(nil)
                return
                }
                let myData = jsonArray[0]["MyPropertyName"]!
                completion(myData)
                }
                task.resume()
                }




                Call



                myFunction(zipCode: "52484") { (str) in 
                if let st = str {
                print(st)
                }
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 23 '18 at 14:12









                Sh_KhanSh_Khan

                46.9k51433




                46.9k51433

















                    這個網誌中的熱門文章

                    Tangent Lines Diagram Along Smooth Curve

                    Yusuf al-Mu'taman ibn Hud

                    Zucchini