Question: Swiftui http request without button

Hello guys,

I´m new to the forum and have a question concerning a http request which should be established without a button clicked. Basically I would like to have everything inside the button´s action tag done automatically without a button clicked.

Thanks in advance.

Nikias

Here is my code from the ts.view :

import SwiftUI



struct ContentView: View {

    

    @State var username: String = "..."

    @State var password: String = "..."

    

    var body: some View {

        

            ZStack {

                VStack {

                        

                    Button(action: {

                        if 1==1 {



                            let myUrl = URL(string: "

                               

                               var request = URLRequest(url:myUrl!)

                               

                               request.httpMethod = "POST"// Compose a query string

                               

                               let postString = "Name=\($username)&Passwort=\($password)";

                               

                               request.httpBody = postString.data(using: String.Encoding.utf8);

                               

                               let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

                                   

                                   if error != nil

                                   {

                                       print("error=\(error)")

                                       return

                                   }

                                   

                                   // You can print out response object

                                   print("response = \(response)")

                          

                                   //Let's convert response sent from a server side script to a NSDictionary object:

                                   do {

                                       let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                                       

                                       if let parseJSON = json {

                                           

                                           // Now we can access value of First Name by its key

                                           let firstNameValue = parseJSON["Name"] as? String

                                           print("firstNameValue: \(firstNameValue)")

                                        let dateien =  firstNameValue?.components(separatedBy: ",")

                    

                    print(dateien)

            

                    

                                       }

                                   } catch {

                                       print(error)

                                   }

                                   }

                                   task.resume()



                        }

                    }) {

                        LoginButtonContent()

                    }

            }

        }

        

    }

}



struct TestView_Previews: PreviewProvider {

    static var previews: some View {

        ContentView()

    }

}


I had to remove the URL.
Hello,

I have now changed some things, but it's still not working.

Code Block
import SwiftUI
struct ContentView4: View {
    
    @State var showingDetail = false
    
    @State var username: String = "."
    @State var password: String = "."
    
    @State var dateien = ["word.png", "vi.png", "text.png", "pp.png", "pdf.png", "ordner.png", "ex.png", "datei.png", "bild.png"]
    
    var body: some View {
        ScrollView(.vertical) {
        ZStack{
            VStack {
                ForEach(0 ..< dateien.count) {
                    Button(action: {
                        print("button pressed")
                        self.showingDetail.toggle()
                    }) {
                    Image("datei")
                    }
                        .scaledToFit()
                        .padding(0)
                
                    Text(self.dateien[$0])
            }
            }
        }
        .sheet(isPresented: $showingDetail) {
                    ts()
                }
        .onAppear { //# This `onAppear` is added to `ZStack{...}`
            doHttpRequest()
        }
    }
    }
    
    mutating func doHttpRequest() {
            let myUrl = URL(string: "http://192.168.1.180/int.php")! //# Trailing semicolon is not needed
            var request = URLRequest(url: myUrl)
            request.httpMethod = "POST"// Compose a query string
            let postString = "Name=\($username)&Passwort=\($password)"
            
            request.httpBody = postString.data(using: .utf8)
            
            let task = URLSession.shared.dataTask(with: request) {
                (data, response, error) in
                
                //# Use if-let when you want to use the unwrapped value
                if let error = error {
                    print("error=\(error)")
                    return
                }
                
                //# Use guard-let when nil has no meaning and want to exit on nil
                guard let response = response else {
                    print("Unexpected nil response")
                    return
                }
                // You can print out response object
                print("response = \(response)")
                
                //Let's convert response sent from a server side script to a NSDictionary object:
                do {
                    //# Use guard-let when nil has no meaning and want to exit on nil
                    guard let data = data else {
                        print("Unexpected nil data")
                        return
                    }
                    //#1 `mutableContainer` has no meaning in Swift
                    //#2 Use Swift Dictionary type instead of `NSDictionary`
                    let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
                    
                    if let parseJSON = json {
                        // Now we can access value of First Name by its key
                        //# Use if-let when you want to use the unwrapped value
                        if let firstNameValue = parseJSON["Name"] as? String {
                            print("firstNameValue: \(firstNameValue)")
                            let dateien =  firstNameValue.components(separatedBy: ",")
                            print(dateien)
                            
                            self.dateien = dateien
                        }
                    }
                } catch {
                    print(error)
                }
            }
            task.resume()
    }
}
struct TestView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView4()
    }
}
struct ts: View {
    var body: some View {
        NavigationView {
        VStack {
            Text("Datei.pdf")
                .font(.system(size: 60))
                .foregroundColor(.black)
                .padding(50)
            Text("+")
                .font(.headline)
                .foregroundColor(.white)
                .padding()
                .frame(width: 220, height: 60)
                .background(Color.yellow)
                .cornerRadius(35.0)
            Text("Datei herunterladen")
                .font(.headline)
                .foregroundColor(.white)
                .padding()
                .frame(width: 220, height: 60)
                .background(Color.blue)
                .cornerRadius(35.0)
            Text("Datei umbenennen")
                .font(.headline)
                .foregroundColor(.white)
                .padding()
                .frame(width: 220, height: 60)
                .background(Color.green)
                .cornerRadius(35.0)
            Text("Datei löschen")
                .font(.headline)
                .foregroundColor(.white)
                .padding()
                .frame(width: 220, height: 60)
                .background(Color.red)
                .cornerRadius(35.0)
            }
        }
    }
}


not working

Sorry, but not working is the worst phrase to tell what is happening.
Please try to tell what's happening precisely instead of just saying not working. I cannot get any clue with only seeing the two words.

And you are missing one thing:

Also, you need to remove mutating from doHttpRequest().

Hello,

Sorry for my bad explaination.

I have now stopped mutating, the app starts fine but as far as the for- loop starts, there is this issue:

Code Block
firstNameValue: pp.png,bild.png,.DS_Store,..,.
["pp.png", "bild.png", ".DS_Store", "..", "."]
ForEach<Range<Int>, Int, TupleView<(ModifiedContent<ModifiedContent<Button<Image>, _AspectRatioLayout>, _PaddingLayout>, Text)>> count (5) != its initial count (9). `ForEach(_:content:)` should only be used for *constant* data. Instead conform data to `Identifiable` or use `ForEach(_:id:content:)` and provide an explicit `id`!
Fatal error: Index out of range: file Swift/ContiguousArrayBuffer.swift, line 444


the app starts fine but as far as the for- loop starts, there is this issue:

Seems we need to go deeper into the code which you have not shown in the opening post.
Generally, you should not add one more questions which is not included in the first post.
You asked Swiftui http request without button, and the issue is answered.


Please try changing the ForEach as follows:
Code Block
ForEach(0 ..< dateien.count, id: \.self) {


If you have something more, you should finish this thread and start a new thread for the new topic.
Question: Swiftui http request without button
 
 
Q