can any body tell me how to connect postgresql in swiftuii am new with swiftui
Post
Replies
Boosts
Views
Activity
how to get page transferred in swiftui button click action
SwiftUI:how to get the secondView showed in full screen when I transfer to secondView from firstView
SwiftUI:I am trying to transfer to secondView from firstView on iPad Pro(11inch) Horizontal screen,the secondView can not be showed in full screenhere is my code:import SwiftUIstruct ContentView: View { @State var showsecondView: Bool = false var body: some View { Button(action: { self.showsecondView.toggle() }) { Text("firstView") }.sheet(isPresented: self.$showsecondView){ secondView(showsecondView: self.$showsecondView) } }}struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() }}struct secondView: View { @Binding var showsecondView: Bool var body: some View { Text("secondView") }}
SwiftUI: how to save the camera photo to somewhere of my apphere is my code :ContentView.swift:import SwiftUI
struct ContentView: View {
@State private var showImagePicker: Bool = false
@State private var image:Image? = nil
var body: some View {
VStack{
image?.resizable()
.scaledToFit()
.clipShape(Circle())
Spacer()
Button("take photo"){
self.showImagePicker = true
}.padding()
.background(Color.green)
.font(.system(size: 40))
.foregroundColor(Color.white)
.cornerRadius(90)
Spacer().frame(width: 0, height: 20, alignment: .topLeading)
}.sheet(isPresented: self.$showImagePicker){
PhotoCaptureView(showImagePicker: self.$showImagePicker, image: self.$image)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}PhotoCapture.swift:import SwiftUI
struct PhotoCaptureView: View {
@Binding var showImagePicker: Bool
@Binding var image:Image?
var body: some View {
ImagePicker(isShown: $showImagePicker, image: $image)
}
}
#if DEBUG
struct PhotoCaptureView_Previews: PreviewProvider {
static var previews: some View {
PhotoCaptureView(showImagePicker: .constant(false), image: .constant(Image("")))
}
}
#endifImagePicker.swift:import Foundation
import SwiftUI
class ImagePickerCoorinator: NSObject, UINavigationControllerDelegate,UIImagePickerControllerDelegate
{
@Binding var isShown: Bool
@Binding var image: Image?
init(isShown: Binding, image: Binding<image?>){
_isShown = isShown
_image = image
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let uiImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
image = Image(uiImage:uiImage)
isShown = false
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
isShown = false
}
}
struct ImagePicker: UIViewControllerRepresentable {
@Binding var isShown: Bool
@Binding var image: Image?
func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext) {
}
func makeCoordinator() -> ImagePickerCoorinator {
return ImagePickerCoorinator(isShown: $isShown, image: $image)
}
func makeUIViewController(context: UIViewControllerRepresentableContext) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
picker.sourceType = .camera
picker.allowsEditing = false
picker.cameraDevice = .front
picker.cameraCaptureMode = .photo
picker.cameraFlashMode = .off
picker.showsCameraControls = true
picker.videoQuality = .type640x480
//picker.cameraViewTransform = picker.cameraViewTransform.scaledBy(x: 1, y: -1)
picker.isEditing = true
return picker
}
}
how can I show the user.name from db with swiftui picker?i have already gotten the data from db and saved in Object Userhere is my code :UserList.swiftimport Foundation
import Combine
class UserList: ObservableObject {
@Published var users: [User] = []
init() {
load()
}
func load() {
let url = URL(string: "http://localhost:3000/user")!
URLSession.shared.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
self.users = try! JSONDecoder().decode([User].self, from: data!)
}
}.resume()
}
}
//struct User: Decodable, Identifiable {
struct User: Decodable {
var id: Int
var name: String
}ContentView.swiftimport SwiftUI
struct ContentView: View {
var body: some View {
Picker(selection: /*@START_MENU_TOKEN@*/.constant(1)/*@END_MENU_TOKEN@*/, label: /*@START_MENU_TOKEN@*/Text("Picker")/*@END_MENU_TOKEN@*/) {
/*@START_MENU_TOKEN@*/Text("1").tag(1)/*@END_MENU_TOKEN@*/
/*@START_MENU_TOKEN@*/Text("2").tag(2)/*@END_MENU_TOKEN@*/
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
how to insert data with Postgrest APII have get data from postgresql with postgrest API in switUI,here is my code for "SELECT * FROM USER;":import Foundation
import Combine
class UserList: ObservableObject {
@Published var users: [User] = []
init() {
load()
}
func load() {
let url = URL(string: "http://localhost:3000/user")!
URLSession.shared.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
self.users = try! JSONDecoder().decode([User].self, from: data!)
}
}.resume()
}
}
//struct User: Decodable, Identifiable {
struct User: Decodable {
var id: Int
var name: String
}
I wat to show data from db in picker. i made it work if I use "data",now I want to change "data" to "data1",then i get the error:"Cannot use instance member 'store' within property initializer; property initializers run before 'self' is available"at line 09.how to resole it?here is my code:Userlist.swiftimport Foundation
import Foundation
import Combine
class Userlist: ObservableObject {
@Published var mainlist: [Mainlist] = []
init() {
load()
}
func load() {
let url = URL(string: "http://localhost:3000/name_v")!
URLSession.shared.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
self.mainlist = try! JSONDecoder().decode([Mainlist].self, from: data!)
}
}.resume()
}
}
struct Mainlist: Decodable{
let name: String
}ContentView.swiftimport SwiftUI
struct ContentView: View {
@ObservedObject var store = Userlist()
@State var selectedStrength = [""]
// var data: [String] = ["str1", "str2", "str3", "str4"]
var data1: [Mainlist] = store.mainlist
var body: some View {
singlePicke(data: data,selectedStrength: $selectedStrength)
}
}
struct singlePicke: View{
let data: [String]
@Binding var selectedStrength: [String]
var body: some View{
GeometryReader{Geometry in
Picker("picker",selection:self.$selectedStrength[0]){
ForEach(00..<self.data.count){raw in<br=""> Text(verbatim:self.data[raw]).tag(self.data[raw])
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
swiftui:I can show data from db in list, but it shown nothing in picker, how can I fix ithere is my code:ContentView.swift:import SwiftUI
struct ContentView: View {
@ObservedObject var model = PostListViewModel()
@State private var selectedStrength = 0
var body: some View {
// List(model.posts) { post in
// Text(String(post.name))
// }
Picker(selection: $selectedStrength, label: Text("picker")) {
ForEach(model.posts) { post in
Text(post.name)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}PostListViewModel.swiftimport Foundation
import SwiftUI
import Combine
final class PostListViewModel: ObservableObject {
init() {
fetchPosts()
}
@Published var posts = [Post]()
private func fetchPosts() {
Webservice().getAllPosts {
self.posts = $0
}
}
}Post.swiftimport Foundation
import SwiftUI
struct Post: Codable,Hashable,Identifiable{
let id: Int
let name: String
}Webservice.swiftimport Foundation
class Webservice{
func getAllPosts(completion: @escaping ([Post]) -> ()){
guard let url = URL(string:
"http://localhost:3000/user")
else{
fatalError("URL is not correct")
}
URLSession.shared.dataTask(with: url){ data, _, _ in
let posts = try!
JSONDecoder().decode([Post].self, from: data!)
DispatchQueue.main.async {
completion(posts)
}
}.resume()
}
}
I took a photo on the secondView,but the photo showed on the ContentView,how can I fix this.I want to take photo on both view(ContentView,SecondView)here is my code :import SwiftUI
struct ContentView: View {
@State var showImagePicker: Bool = false
@State var image:Image? = nil
@State var showsecondView: Bool = false
@State var show:Bool = false
var body: some View {
ZStack {
VStack{
image?.resizable()
.scaledToFit()
.clipShape(Circle())
Button("take photo"){
self.showImagePicker = true
//self.showEntryView.toggle()
}.padding()
Button(action: {
self.showsecondView.toggle()
}) {
Text("firstView")
}
}
.sheet(isPresented: self.$showImagePicker){
PhotoCaptureView(showImagePicker: self.$showImagePicker, image: self.$image)
}
if self.showsecondView {
SecondView(showsecondView: self.$showsecondView,showImagePicker:self.$showImagePicker)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.red)
.animation(.easeInOut)
.transition(.move(edge: .bottom))
}}
}
}
struct SecondView: View {
@Binding var showsecondView: Bool
@Binding var showImagePicker: Bool
@State var image:Image? = nil
var body: some View {
ZStack(alignment: .leading) {
VStack {
Button(action: {
self.showsecondView = false
}) {
Text("dismiss")
}
Text("secondView")
image?.resizable()
.scaledToFit()
.clipShape(Circle())
Button("take photo"){
self.showImagePicker = true
//self.showEntryView.toggle()
}.padding()
// .sheet(isPresented: self.$showImagePicker){
// PhotoCaptureView(showImagePicker: self.$showImagePicker, image: self.$image)
// }
}
if self.showImagePicker {
PhotoCaptureView(showImagePicker: self.$showImagePicker, image: self.$image)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.red)
.animation(.easeInOut)
.transition(.move(edge: .bottom))
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
swiftUI:how to get button enabled until all checkbox get checkedhere is my code:i want get button(logout) enabled until checkbox(check1~check5) all checkedCheckView.swift:import SwiftUI
struct CheckView: View {
@State var isChecked:Bool = false
var title:String
var count:Int = 0
func toggle(){isChecked = !isChecked}
var body: some View {
HStack{
Button(action: toggle) {
Image(systemName: isChecked ? "checkmark.square" : "square")
}
Text(title)
}
}
}
#if DEBUG
struct CheckView_Previews: PreviewProvider {
static var previews: some View {
CheckView(title:"Title")
}
}
#endifExitCheckListData.swift:import Foundation
let exitCheckListdata = [
ExitCheckListItem(id:0,title: "check1"),
ExitCheckListItem(id:1,title: "check2"),
ExitCheckListItem(id:2,title: "check3"),
ExitCheckListItem(id:3,title: "check4"),
ExitCheckListItem(id:4,title: "check5")
]ContentView.swift:List(exitCheckListdata){ item in
CheckView(isChecked: item.isChecked, title: item.title)
}
.font(.title)
Button(action: {
}) {
Text("logout")
}
I am trying insert into db use post method in swiftand i can not get the response.statusCode of post method in swiftui viewhow can i fix itimport SwiftUI
struct ContentView: View {
@State var resp:Int = 0
var body: some View {
VStack{
Text("Hello, World!")
Button(action: {
self.resp = postAdd()
print("view\(self.resp)")
}) {
Text(/*@START_MENU_TOKEN@*/"Button"/*@END_MENU_TOKEN@*/)
.background(self.resp == 201 ? Color.green : Color.gray)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
func postAdd() ->Int{
let url = URL(string: "http://localhost:3000/user")
var request = URLRequest(url: url!)
var resp = 0
request.httpMethod = "POST"
let urlstr = "id=5&name=aaa"
request.httpBody = urlstr.data(using: .utf8)!
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if error == nil, let data = data, let response = response as? HTTPURLResponse {
print("Content-Type: \(response.allHeaderFields["Content-Type"] ?? "")")
print("statusCode: \(response.statusCode)")
resp = response.statusCode
print(String(data: data, encoding: .utf8) ?? "")
}
}.resume()
return resp
}
for example :how to change the image border color when i click a button