Search code examples
iosswift

URLSession requesting JSON array from server not working


guard let url =  URL(string:"https://blaaaajo.de/getHiddenUsers.php") else { return }
    
let postString = "blockedUsers=245,1150"
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = postString.data(using: String.Encoding.utf8);

do {
    let (responseString, _) = try await URLSession.shared.data(for: request)
    
    if let decodedResponse = try? JSONDecoder().decode([HiddenUsersModel].self, from: responseString){
        gettingBlockedUsers = false
        blockedUsers = decodedResponse
    }
    
} catch {
    print("Error: \(error)")
}

the HiddenUsersModel:

struct HiddenUsersModel: Codable {
    var userid: Int
    var nickname: String
}

I'm always getting data not valid

The url and the POST key blockedUsers with the value 245,1150 is 100% correct, I'm also using this API for the web and Android app.

The code on server side doesn't get executed though, not even at the beginning of the PHP script. So no JSON response is generated.

The error I'm getting:

Error: Error Domain=NSURLErrorDomain Code=-999 "Abgebrochen" UserInfo={NSErrorFailingURLStringKey=https://blaaaajo.de/do_getblockedusers.php, NSErrorFailingURLKey=https://blaaaajo.de/do_getblockedusers.php, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <33660134-3AEC-4416-A917-C0FC64934DB5>.<7>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <33660134-3AEC-4416-A917-C0FC64934DB5>.<7>, NSLocalizedDescription=Abgebrochen}

according to the checked answer in How to fix "NSURLErrorDomain error code -999" in iOS it's another request is made before the previous request is completed but it's not true, when I print something before do then it gets printed only once


Solution

  • Ok the problem was really due to task being called twice. The reson for that was that I have passed the showBlockedUsers boolean across multiple views. So passing it leads to for what ever reason the view being called twice and with that interrupting the api, even if you have something like

    if(apiCalled){
        return
    }
        
    apiCalled = true
    
    // API request
    

    This will not prevent the error from happening.