I need to make an app on MacOS with a single button and a single text field, so when I press the button , particular data (mySubstring) from internet will appear in text box. I've tried to do that in Swift Playground , it works fine and here is the code:
import Foundation
var info: String = ""
let mySubstring = ""
let myString = String(mySubstring)
var request = URLRequest(url: URL(string: "https://api.openweathermap.org/data/2.5/weather?id=1502026&appid=df10ddc41c923a4f0e93ffc67631f0c5")!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request)
{ data, response, error in
info = String(decoding: data!, as: UTF8.self)
let index = info.index(info.startIndex, offsetBy: 16)
let endindex = info.index(info.startIndex, offsetBy: 22)
let mySubstring = info[index...endindex]
print(mySubstring)
}
task.resume()
but when I try to gather it all to a Project. I need to do in App exactly what I wrote, thereafter I will extend my tasks.
Thanks in advance !
CodePudding user response:
As I mentioned in my comments, your code shows very clearly that you have to learn the basics at: https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html
Then you have to do the tutorial at: https://developer.apple.com/tutorials/swiftui/
Without knowing the basics you are not going to understand the answers from SO.
Here is some example code to get you going:
struct ContentView: View {
@State var mySubstring = ""
var body: some View {
VStack {
Text("Testing this")
HStack {
Button(action: { loadData() }) {
Text("Push me")
}
TextField("", text: $mySubstring) // <-- should use Text(mySubstring)
.frame(width: 150.0, height: 20.0)
}
.frame(width: 400.0, height: 200.0)
}
}
func loadData() {
var request = URLRequest(url: URL(string: "https://api.openweathermap.org/data/2.5/weather?id=1502026&appid=xxxxx")!)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) { data, response, error in
if let theData = data {
let info = String(data: theData, encoding: .utf8)!
let index = info.index(info.startIndex, offsetBy: 16)
let endindex = info.index(info.startIndex, offsetBy: 22)
self.mySubstring = String(info[index...endindex])
}
}.resume()
}
}