Last active
August 18, 2020 21:57
-
-
Save DaisukeNagata/3659f5ba5e984d77f43ea4d5e99f6757 to your computer and use it in GitHub Desktop.
SwiftUI_ Language
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import Combine | |
struct LanguageResponse: Decodable { | |
var statusCode: Int | |
var body: String | |
} | |
struct ContentView: View { | |
@State var st = String() | |
@State var st2 = String() | |
@State var languageSet = String() | |
@State var cancellable: Cancellable? | |
var body: some View { | |
VStack { | |
TextField("言語", text: $languageSet) | |
.textFieldStyle(RoundedBorderTextFieldStyle()) | |
.frame(height: 100) | |
.padding() | |
TextField("翻訳", text: $st, | |
onCommit: { | |
self.st2 = self.lan() | |
self.st = "" | |
}) | |
.textFieldStyle(RoundedBorderTextFieldStyle()) | |
.frame(height: 100) | |
.padding() | |
Text(self.st2) | |
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center) | |
} | |
} | |
func lan() -> String { | |
let myURL1 = "Make API" | |
let encodeUrlString: String = myURL1.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "" | |
guard let url = URL(string: encodeUrlString) else { return "" } | |
var request = URLRequest(url: url) | |
request.addValue("application/json", forHTTPHeaderField: "Content-Type") | |
request.httpMethod = "GET" | |
cancellable = URLSession.shared.dataTaskPublisher(for: request) | |
.map { $0.data } | |
.decode(type: LanguageResponse.self, decoder: JSONDecoder()) | |
.receive(on: RunLoop.main) | |
.eraseToAnyPublisher() | |
.sink(receiveCompletion: { completion in | |
switch completion { | |
case .finished: | |
break | |
case .failure(let error): | |
fatalError(error.localizedDescription) | |
} | |
}, receiveValue: { user in | |
print(user, "user") | |
self.st2 = user.body | |
}) | |
return self.st2 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://twitter.com/dbank0208/status/1295686563666395136?s=20