I am new to SwiftUI and developing, and trying to make a drug searching app I am in the process of making a search text field, that shows a list of drug name suggestions
This is the array of data and the text field inside a struct.
@State var drugNameSearch = [DrugNameSearch]()
TextField("Insert Drug Name" , text: $drugName, onEditingChanged: { isEdited in
self.isEdited = isEdited
self.isDrugSearched = isEdited
})
.frame(height:geometry.size.height/35)
.onChange(of: drugName, perform: { value in
self.fetchData()
})
if isDrugSearched == true {
ForEach(drugNameSearch.filter({drugName.isEmpty ? false : $0.name.contains(drugName) }), id: \.self) { item in
HStack{
HStack{
Image(systemName: "magnifyingglass")
Text(item.name)
}
.onTapGesture{self.drugName = item.name}
Spacer()
}
}
}
else{}
And below is the method with the problem. Without the "&item_name=(drugName)", the app launches fine but works with limited data fetched. With the code below, the app crashes with the URL unwrapping issue. Please give me advice...
private func fetchData() {
print("Drug Name Search Attempted!")
let url = URL(string: "http://apis.data.go.kr/1471000/DrugPrdtPrmsnInfoService/getDrugPrdtPrmsnDtlInq?serviceKey=SERVICEKEY&item_name=\(drugName)&numOfRows=10&type=json")
URLSession.shared.dataTask(with: url!){(data, response, error) in
do {
if let drugNameData = data {
let decodedData = try JSONDecoder().decode(DrugFetch.self, from: drugNameData)
DispatchQueue.main.async {
self.drugNameSearch = decodedData.body.items
}
} else {
print("No Data for drugNameSearch")
}
}
catch {
print("drugNameSearch Fetching Error: \(error)")
}
}//URLSession
.resume()
}