今回の内容
・ChapGPTのAPIを使ってみる
・レスポンスを受け取って回答をTextViewに表示をする
Contents 非表示
完成形
APIキーの取得
取得サイト: https://beta.openai.com/account/api-keys
ChatGPT
を初めて使う人は先にサインアップが必要です。
SPM (Swift Package Manager) のインストール
検索URL: https://github.com/adamrushy/OpenAISwift
Storyboard
コード
import UIKit
import OpenAISwift
class ChatGPTViewController: UIViewController {
// MARK: - Properties
private let openAI = OpenAISwift(authToken: "<#自分のAPIキー#>")
// MARK: - Outlets
@IBOutlet private weak var questionTextField: UITextField!
@IBOutlet private weak var questionSendButton: UIButton!
@IBOutlet private weak var answerTextView: UITextView!
@IBOutlet private weak var loadingView: UIActivityIndicatorView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
// MARK: Keyboard Dismissal
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
// MARK: - Private Methods
private func configureView() {
questionTextField.delegate = self
questionSendButton.layer.cornerRadius = 10
answerTextView.layer.cornerRadius = 10
answerTextView.isEditable = false
loadingView.isHidden = true
}
private func startAnimation() {
loadingView.isHidden = false
loadingView.startAnimating()
}
private func stopAnimation() {
loadingView.stopAnimating()
loadingView.isHidden = true
}
// MARK: - Actions
@IBAction func sendQuestionToChatGPT(_ sender: Any) {
questionTextField.resignFirstResponder()
startAnimation()
guard let userQuestion = questionTextField.text, !userQuestion.trimmingCharacters(in: .whitespaces).isEmpty else {
stopAnimation()
return
}
answerTextView.text = "Q: \(userQuestion)"
print("Request Sent\nQuestion: \(userQuestion)")
openAI.sendCompletion(with: userQuestion, maxTokens: 500) { [weak self] result in
switch result {
case .success(let success):
print("Request Successful\n-------------------------------------------------")
DispatchQueue.main.async {
self?.answerTextView.text = ("Q: \(userQuestion)\n\(success.choices.first?.text ?? "")")
self?.stopAnimation()
}
case .failure(let error):
print("Request Failed: \(error)")
DispatchQueue.main.async {
self?.stopAnimation()
}
}
}
questionTextField.text = ""
}
}
// MARK: - Extensions
extension ChatGPTViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}