carson-katri / swift-request

Declarative HTTP networking, designed for SwiftUI
MIT License
731 stars 41 forks source link

Can't set request body #23

Closed samuelbles07 closed 4 years ago

samuelbles07 commented 4 years ago

I followed the example in Readme but it always show error Type 'TestTest.Body' (aka 'some View') has no member 'init'.

XCode 11.4.1 IOS 13.4

Test Code

import SwiftUI
import Request

struct TestTest : View {
    @State var myData: String = "dono"
    let myToken = "12345"

    var body: some View {
    NavigationView {        

        VStack {
            Text(self.myData)

            Button(action: {
                Request {
                    Url("https://myurl.com/")
                    Method(.post)
                    Header.ContentType(.json)
                    Header.Any(key: "accessToken", value: self.myToken)

                    Body(Json([
                        "data": "abcd"
                    ]).stringified)
                }
                .onString { data in
                    self.myData = data
                }
                .onError { error in
                    print(error)
                }
                .call()

            }
            ) {
                Text("update")
            }
        }
        .navigationBarTitle(Text("Todos"))
        }
    }
}

struct TestTest_Previews: PreviewProvider {
    static var previews: some View {
        TestTest()
    }
}
carson-katri commented 4 years ago

Ah, so the issue seems to be that Body refers to the associatedtype Body included with all SwiftUI views. A workaround is to declare a typealias at the root of the project:

import Request
typealias RequestBody = Body

Then instead of using Body in your request, you can use:

Request {
   ...
   RequestBody(Json([...]))
}

You should only have to use this workaround if you're calling using Request from inside a SwiftUI View.

carson-katri commented 4 years ago

I'm closing this due to inactivity