Swift URL Session and URL Request not working

I am getting very similar problems with this post , but I do not quite understand the answer. I created a completion handler, but it does not work as expected.

func updateTeam(teamID: Int) {
    startConnection {NSArray, Int in
        //Do things with NSArray
    }
}

func startConnection(completion: (NSArray, Int) -> Void) {
    let url = URL(string: "http://www.example.com/path")
    var request : URLRequest = URLRequest(url: url!)
    request.httpMethod = "POST"
    let postString = "a=\(Int(teamInput.text!)!)"
    request.httpBody = postString.data(using: .utf8)

    let dataTask = URLSession.shared.dataTask(with: request) {
        data,response,error in
        print("anything")
        do {
            if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
                self.teamResult = jsonResult
                print(jsonResult)
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

    }
    dataTask.resume()

    completion(NSArray(object: teamResult), Int(teamInput.text!)!)
}

Nothing in the dataTask statement works, or at least it does not complete before I try to use the given data. What is wrong with this completion handler?

Thank you in advance!

+4
source share
3 answers

Your code is not structured correctly.

URLSessionCreates tasks that are run asynchronously. You configure the task and either go through the completion block or configure the delegate.

task.resume() , .

, ( , ).

, URLSession . UIKit , .

@keithbhunter , . , , :

func startConnection(completion: (NSArray, Int) -> Void) {
    let url = URL(string: "http://www.example.com/path")
    var request : URLRequest = URLRequest(url: url!)
    request.httpMethod = "POST"
    let postString = "a=\(Int(teamInput.text!)!)"
    request.httpBody = postString.data(using: .utf8)

    let dataTask = URLSession.shared.dataTask(with: request) {
        data,response,error in
        print("anything")
        do {
            if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
                self.teamResult = jsonResult
                print(jsonResult)
                //Use GCD to invoke the completion handler on the main thread
                DispatchQueue.main.async() {
                  completion(NSArray(object: teamResult), Int(teamInput.text!)!)
                }
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
    dataTask.resume()
}

, teamInput.text , teamInput.text Int. , , int, teamInput.text:

func startConnection(completion: (NSArray?, Int?) -> Void) {

:

let value: Int? = teamInput.text != nil ? Int(teamInput.text!) : nil
completion(NSArray(object: teamResult), value)
+4

, .

func updateTeam(teamID: Int) {
    startConnection {array, teamId, error in
        // Do things with NSArray or handle error
    }
}

func startConnection(completion: @escaping (NSArray?, Int, Error?) -> Void) {
    let url = URL(string: "http://www.example.com/path")
    var request : URLRequest = URLRequest(url: url!)
    request.httpMethod = "POST"
    let postString = "a=\(Int(teamInput.text!)!)"
    request.httpBody = postString.data(using: .utf8)

    let dataTask = URLSession.shared.dataTask(with: request) {
        data,response,error in
        print("anything")
        do {
            if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
                self.teamResult = jsonResult
                print(jsonResult)
                DispatchQueue.main.async() {
                    completion(NSArray(object: self.teamResult), Int(teamInput.text!)!, nil)
                }
        } catch let error as NSError {
            print(error.localizedDescription)
            DispatchQueue.main.async() {  
                completion(nil, Int(teamInput.text!)!, error)
            }
        }

    }
    dataTask.resume()
}
+2

Try the following:

let urlString = "www.yoururl.com"
let url = URL(string: string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)

It has helped me many times

0
source

Source: https://habr.com/ru/post/1671927/


All Articles