質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

1380閲覧

OAuthSwiftでTwitterにログインしたい

tmyk1979

総合スコア145

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2022/02/02 01:08

編集2022/02/02 13:46

前提・実現したいこと

OAuthSwiftを使って自作アプリでTwitterにログインしたい。

ここに質問の内容を詳しく書いてください。

https://qiita.com/haru15komekome/items/10bd68df52ad72233b5c
・・・をほぼそのままコピペして、OAuthSwiftを使ってTwitterにログインするだけの
アプリを作ってみたのですが、ログインできずに困っています。

以下のソースコードをどのように直せばログインできるかご教示いただけますようお願いします。

発生している問題・エラーメッセージ

The operation couldn’t be completed. (OAuthSwiftError error -11.)

該当のソースコード

Swift

1// ViewController.swift 2 3import UIKit 4import OAuthSwift 5 6struct Const { 7 static let consumerKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" 8 static let consumerSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" 9} 10 11class ViewController: UIViewController { 12 13 var oauthswift: OAuthSwift? 14 15 override func viewDidLoad() { 16 super.viewDidLoad() 17 doOAuthTwitter() 18 view.backgroundColor = .blue 19 } 20 21 /// OAuth1ログイン処理 22 func doOAuthTwitter(){ 23 24 let oauthswift = OAuth1Swift( 25 consumerKey: Const.consumerKey, 26 consumerSecret: Const.consumerSecret, 27 requestTokenUrl: "https://api.twitter.com/oauth/request_token", 28 authorizeUrl: "https://api.twitter.com/oauth/authorize", 29 accessTokenUrl: "https://api.twitter.com/oauth/access_token" 30 ) 31 self.oauthswift = oauthswift 32 oauthswift.authorizeURLHandler = getURLHandler() 33 34 // コールバック処理 35 oauthswift.authorize(withCallbackURL: URL(string: "TwitterLoginSampleOAuth://")!, 36 completionHandler: 37 { result in 38 switch result { 39 case .success(let (credential, _, _)): 40 print(credential.oauthToken) 41 print(credential.oauthTokenSecret) 42 self.showAlert(credential: credential) 43 print("success") 44 case .failure(let error): 45 print(error.localizedDescription) 46 print("failure") 47 } 48 } 49 ) 50 } 51 52 /// ログイン画面起動に必要な処理 53 /// 54 /// - Returns: OAuthSwiftURLHandlerType 55 func getURLHandler() -> OAuthSwiftURLHandlerType { 56 if #available(iOS 9.0, *) { 57 let handler = SafariURLHandler(viewController: self, oauthSwift: self.oauthswift!) 58 handler.presentCompletion = { 59 print("Safari presented") 60 } 61 handler.dismissCompletion = { 62 print("Safari dismissed") 63 } 64 return handler 65 } 66 return OAuthSwiftOpenURLExternally.sharedInstance 67 } 68 69 /// アラート表示 70 /// 71 /// - Parameter credential: OAuthSwiftCredential 72 func showAlert(credential: OAuthSwiftCredential) { 73 var message = "oauth_token:\(credential.oauthToken)" 74 if !credential.oauthTokenSecret.isEmpty { 75 message += "\n\noauth_token_secret:\(credential.oauthTokenSecret)" 76 } 77 let alert = UIAlertController(title: "ログイン", 78 message: message, 79 preferredStyle: UIAlertController.Style.alert) 80 alert.addAction(UIAlertAction(title: "OK", 81 style: UIAlertAction.Style.default, handler: nil)) 82 self.present(alert, animated: true, completion: nil) 83 } 84} 85

Swift

1 2// appDelegate.swift 3 4import UIKit 5import OAuthSwift 6 7@UIApplicationMain 8class AppDelegate: UIResponder, UIApplicationDelegate { 9 10 var window: UIWindow? 11 12 /****追加した処理****/ 13 func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { 14 applicationHandle(url: url) 15 return true 16 } 17} 18 19extension AppDelegate { 20 /// コールバック処理 21 /// 22 /// - Parameter url: URL 23 func applicationHandle(url: URL) { 24 if (url.host == "oauth-callback") { 25 // URLを指定する場合はここで設定する 26 OAuthSwift.handle(url: url) 27 } else { 28 OAuthSwift.handle(url: url) 29 } 30 } 31}

Swift

1 2// info.plist 3<?xml version="1.0" encoding="UTF-8"?> 4<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 5<plist version="1.0"> 6<dict> 7 <key>CFBundleURLTypes</key> 8 <array> 9 <dict> 10 <key>CFBundleURLName</key> 11 <string></string> 12 <key>CFBundleURLSchemes</key> 13 <array> 14 <string>TwitterLoginSampleOAuth</string> 15 </array> 16 </dict> 17 </array> 18 <key>CFBundleDevelopmentRegion</key> 19 <string>$(DEVELOPMENT_LANGUAGE)</string> 20 <key>CFBundleExecutable</key> 21 <string>$(EXECUTABLE_NAME)</string> 22 <key>CFBundleIdentifier</key> 23 <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> 24 <key>CFBundleInfoDictionaryVersion</key> 25 <string>6.0</string> 26 <key>CFBundleName</key> 27 <string>$(PRODUCT_NAME)</string> 28 <key>CFBundlePackageType</key> 29 <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string> 30 <key>CFBundleShortVersionString</key> 31 <string>1.0</string> 32 <key>CFBundleVersion</key> 33 <string>1</string> 34 <key>LSRequiresIPhoneOS</key> 35 <true/> 36 <key>UIApplicationSceneManifest</key> 37 <dict> 38 <key>UIApplicationSupportsMultipleScenes</key> 39 <false/> 40 <key>UISceneConfigurations</key> 41 <dict> 42 <key>UIWindowSceneSessionRoleApplication</key> 43 <array> 44 <dict> 45 <key>UISceneConfigurationName</key> 46 <string>Default Configuration</string> 47 <key>UISceneDelegateClassName</key> 48 <string>$(PRODUCT_MODULE_NAME).SceneDelegate</string> 49 <key>UISceneStoryboardFile</key> 50 <string>Main</string> 51 </dict> 52 </array> 53 </dict> 54 </dict> 55 <key>UILaunchStoryboardName</key> 56 <string>LaunchScreen</string> 57 <key>UIMainStoryboardFile</key> 58 <string>Main</string> 59 <key>UIRequiredDeviceCapabilities</key> 60 <array> 61 <string>armv7</string> 62 </array> 63 <key>UISupportedInterfaceOrientations</key> 64 <array> 65 <string>UIInterfaceOrientationPortrait</string> 66 <string>UIInterfaceOrientationLandscapeLeft</string> 67 <string>UIInterfaceOrientationLandscapeRight</string> 68 </array> 69 <key>UISupportedInterfaceOrientations~ipad</key> 70 <array> 71 <string>UIInterfaceOrientationPortrait</string> 72 <string>UIInterfaceOrientationPortraitUpsideDown</string> 73 <string>UIInterfaceOrientationLandscapeLeft</string> 74 <string>UIInterfaceOrientationLandscapeRight</string> 75 </array> 76</dict> 77</plist> 78

試したこと

TwitterDeveloper Portal側の設定は行いました。
swifterDemoiOSは動いたので、設定は合っていると思うのですがCallbackURLは以下のように書き換えては失敗するという事を繰り返しています。

https://muchan611.hatenablog.com/entry/2019/07/21/130059
・・・を参考に、callbackURLを「oauth-swift://oauth-callback/twitter」にしてみましたが、同様のエラーが出ました。

https://qiita.com/Kyome/items/8f86ad20dec4d2a10854
・・・を参考に、

TARGETS -> Info -> URL Types -> URL Schemes は自分のアプリ名など任意の文字列(ここではmyappとする)
OAuth1Swift.authorize()で指定するCallbackURLは"myapp://oauth-callback/twitter"にする
OAuthSwift.handle(url:)を呼ぶ前の条件分岐はurl.host == "oauth-callback"にする
Twitter Appsのアプリ設定項目のCallback URLはmyapp://を入力する

・・・としてみたのですが、同様のエラーが出ました。

「The operation couldn’t be completed. (OAuthSwiftError error -11.)」と検索して何となくcallbackURLがおかしいのではないかと思ったのですが、どのようにすれば良いかは分かりませんでした。

https://www.fixes.pub/program/19863.html
・・・を参考に、

Swift

1 override func viewDidLoad() { 2 super.viewDidLoad() 3// doOAuthTwitter() 4 view.backgroundColor = .blue 5 6 print("BEFORE OAUTHSWIFT") 7 oauthswift = OAuth1Swift( 8 consumerKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 9 consumerSecret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 10 requestTokenUrl: "https://api.twitter.com/oauth/request_token", 11 authorizeUrl: "https://api.twitter.com/oauth/authorize", 12 accessTokenUrl: "https://api.twitter.com/oauth/access_token" 13 ) 14 print("AFTER OAUTHSWIFT") 15 handle = oauthswift.authorize(// ここでエラーになる 16 withCallbackURL: URL(string: "oauth-swift://oauth-callback/twitter")!, 17 success: { credential, response, parameters in 18 print("OAuthToken: \(credential.oauthToken)") 19 print("OAuthSecret: \(credential.oauthTokenSecret)") 20 print("User ID: \(parameters["user_id"]!)") 21 // Do your request 22 }, 23 failure: { error in 24 print(error.localizedDescription) 25 print(self.handle) 26 } 27 ) 28 // Do any additional setup after loading the view, typically from a nib. 29 } 30 31 }

・・・としてみたのですが、handle = oauthswift.authorize(のところで「Type of expression is ambiguous without more context」というエラーが出て、型を宣言してあげればこのエラーを解消できるということは分かったのですが、型が分からないためこのエラーの解消方法が分かりません。
当てずっぽうで「OAuthSwiftRequestHandle!」としてみたのですが違っていました。

補足情報(FW/ツールのバージョンなど)

Xcode11.6
iPhoneSE
iOS13.6

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

tmyk1979

2022/02/02 13:39

MasakiHoriさま、アドバイスありがとうございます。 TwitterのDeveloper Portal側の設定は終わっています。 swifteriOSのデモアプリは動いたので設定は合っていると思うのですが、 CallbackURLだけは質問に書いたように色々変えては失敗するという事を 繰り返しています。
guest

回答1

0

自己解決

OAuthでログインする事は諦め、Swifterを使ったらログインできました。
Swifterも古くエラーや警告を修正する必要があるので、フレームワークに頼らず
ログインできるよう勉強を進めていこうと思います。

投稿2022/02/08 07:29

tmyk1979

総合スコア145

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問