swiftでopenAIを直接利用する方法

pod 'Alamofire'
import Alamofire
//OpenAI
struct OpenAIConfiguration {
    let apiKey: String
}
let configuration = OpenAIConfiguration(apiKey: "hage")


func generateTranslationPrompt(inputText: String) -> String {
    let promptTemplate = "xxxxxしろや。:  \(inputText)"
    return promptTemplate
}

func callText(model: String,inputText: String, completion: @escaping (String?, Error?) -> Void) {
    let prompt = generateTranslationPrompt(inputText: inputText)
    
    let messages: [[String: Any]] = [
            ["role": "system", "content": "あなたはxxxxxです。"],
            ["role": "user", "content": prompt]
        ]
        
        let parameters: [String: Any] = [
            "model": model,
            "messages": messages,
            "temperature": 0.3,
            "top_p": 1.0,
            "frequency_penalty": 0.0,
            "presence_penalty": 0.0
        ]
        
        let headers: HTTPHeaders = [
            "Authorization": "Bearer \(configuration.apiKey)"
        ]
        
    AF.request("https://api.openai.com/v1/chat/completions", method: .post, parameters: parameters, encoding: JSONEncoding.default,
               headers: headers).responseJSON { response in
            switch response.result {
            case .success(let value):
                if let jsonResponse = value as? [String: Any],
                   let choices = jsonResponse["choices"] as? [[String: Any]],
                   let firstChoice = choices.first,
                   let message = firstChoice["message"] as? [String: Any],
                   let text = message["content"] as? String {
                    completion(text, nil)
                } else {
                    completion(nil, NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to parse response"]))
                }
            case .failure(let error):
                completion(nil, error)
            }
        }
    
}

そんで呼びたいところで使う

let orgString = "おはよう"
        callText(model: "gpt-3.5-turbo",inputText: "\(orgString)") { (convertText, error) in
            if let error = error {
                print("Error1: \(error)")
            } else if let convertText = convertText {
                print("Translated text: \(convertText)")
            }
        }

You don’t have write permissions for the /usr/bin directory.

iOSを1年ぶりに触ったら下記の通りエラー

pod update
[!] `GoogleAppMeasurement` requires CocoaPods version `>= 1.10.2`, which is not satisfied by your current version, `1.10.1`.

cocoapodsのバージョンをあげる
sudo gem install cocoapods

ERROR: While executing gem … (Gem::FilePermissionError)
You don’t have write permissions for the /usr/bin directory.

一応成功
sudo gem install cocoapods -n /usr/local/bin

Objective-Cからswiftを呼ぶ[Objective-c,Swift]

久しぶりに毒林檎を弄ったので備忘録として。

 

Objective-c から Swift

 

//Need

//Call From Objective-C To swift

#import "MyApp-Swift.h"

SwiftからObjective-c

import Foundation

//obj-cからアクセスするのに必要
@objcMembers
class SharedInfos: NSObject {
    static let shared: SharedInfos = SharedInfos()
   
    func someFlag() -> Bool {
       
            return true
        }
    
}

presentViewController[swift,Objective-C,ios13]

iOS13から画面遷移をするとポップアップしたようになりスワイプでもviewを消せるようになった。

私のアプリでA→B(問題があるView、スワイプ)→A→B(dissmissボタンを押す)この時に何故か落ちる。

Fatal Exception: NSInternalInconsistencyException Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.

メインスレッドにキューを入れればいいようだが入れても直らなかった。

iosにそんな時間をかけたくなかったのでスワイプをそもそもできなくした。(画面をフルにした。)

Appdelegate.m obj-c

FilterNewShowViewController *shopViewC = [[FilterNewShowViewController alloc] initWithNibName:@"FilterNewShowViewController" bundle:[NSBundle mainBundle]];

>>>>shopViewC.modalPresentationStyle =  UIModalPresentationFullScreen;  

>>>>shopViewC.modalInPopover = YES;  //スワイプで消えなくなる。

self.window.rootViewController = shopViewC;

[self.window makeKeyAndVisible];
Viewcontroller.m obj-c
FilterNewShowViewController *shopViewC = [[FilterNewShowViewController alloc] initWithNibName:@"FilterNewShowViewController" bundle:[NSBundle mainBundle]];
>>>>shopViewC.modalPresentationStyle = UIModalPresentationFullScreen; //表示形式の選択
>>>>shopViewC.modalInPopover = YES; //スワイプで消えなくなる。
[self presentViewController:shopViewC animated:YES completion:nil];
Viewcontroller.swift
let vc = UIViewController()
>>>>vc.modalPresentationStyle = .fullScreen;
>>>>vc.isModalInPresentation = true;
present(vc, animated: false, completion: nil)

NSDateから曜日を取得する[Objective-C,Swift]

Objective-C

NSDate *date = [NSDate date]; 
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit fromDate:date]; 
NSInteger weekday = [components weekday];

Swift

var date = NSDate()
var calender = NSCalendar.currentCalendar()
var components = calender.components(NSCalendarUnit.YearCalendarUnit|NSCalendarUnit.MonthCalendarUnit|NSCalendarUnit.DayCalendarUnit|NSCalendarUnit.WeekdayCalendarUnit, fromDate: date)
var weekday = components.weekday

weekdayは1=日曜日〜7=土曜日です。

日曜日月曜日火曜日水曜日木曜日金曜日土曜日
1234567