123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369 |
- //
- // SettingsViewController.swift
- // AIPaint
- //
- // Created by Fengyu He on 2022/11/29.
- //
- import UIKit
- import SnapKit
- import SwiftyJSON
- import AuthenticationServices
- class SettingsViewController: UIViewController, UITextFieldDelegate {
- var settingsTableView: UITableView!
-
- var headers: [String]!
- var settingsSection: Int!
-
- let welcomeView: UIView = {
- var view = UIView()
- view.layer.borderWidth = 1
- view.layer.borderColor = UIColor.systemGray.cgColor
- view.layer.cornerRadius = 14
- return view
- }()
-
- lazy var welcomeText: UILabel = {
- var label = UILabel()
- label.numberOfLines = 0
- label.lineBreakMode = .byWordWrapping
- label.text = "感谢你参与画酱的封闭测试,见证画酱的诞生!\n你可以加入QQ群来对本 App 提出宝贵意见:390674039 \n此 App 目前还在初期稳定行测试阶段,如果你有什么功能上的需求,或是对于 App 的设计有任何的建议,欢迎进群与我讨论!\n \n暂时还没适配暗黑模式,请在正常模式使用此 App。"
- return label
- }()
-
- lazy var userInfoCell = UserInfoCell(style: .default, reuseIdentifier: "UserInfo")
-
- lazy var userIdLabel: UILabel = {
- var label = UILabel()
- return label
- }()
-
- var signInWithAppleButton = ASAuthorizationAppleIDButton(authorizationButtonType: .default, authorizationButtonStyle: .black)
- let userDefaults = UserDefaults.standard
- let netTools = NetTools()
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- if UITraitCollection.current.userInterfaceStyle == .dark {
- view.backgroundColor = .black
- welcomeText.textColor = .white
- userIdLabel.textColor = .white
- } else {
- view.backgroundColor = .white
- welcomeText.textColor = .black
- userIdLabel.textColor = .black
- }
- self.title = "设置"
- self.settingsTableView = UITableView(frame: self.view.frame, style: .insetGrouped)
- self.settingsTableView.delegate = self
- self.settingsTableView.dataSource = self
- self.settingsTableView.register(UITableViewCell.self, forCellReuseIdentifier: "SettingsCell")
- view.addSubview(settingsTableView)
-
- headers = [
- "用户协议",
- "关于"
- ]
-
- settingsSection = userDefaults.bool(forKey: UserDefaultKeys.UserInfo.isLogin) ? 3 : 2
-
- signInWithAppleButton.cornerRadius = 8.0
- signInWithAppleButton.addTarget(self, action: #selector(handleAuthorizationAppleIDButtonPress), for: .touchUpInside)
- view.addSubview(signInWithAppleButton)
- if #available(iOS 15.0, *) {
- signInWithAppleButton.isHidden = false
- } else {
- signInWithAppleButton.isHidden = true
- }
-
- signInWithAppleButton.snp.makeConstraints { (make) in
- make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(5)
- make.centerX.equalTo(view.safeAreaLayoutGuide.snp.centerX)
- make.width.equalTo(view.safeAreaLayoutGuide.snp.width).multipliedBy(0.35)
- make.height.equalTo(view.safeAreaLayoutGuide.snp.height).multipliedBy(0.05)
- }
- }
-
- override func viewDidAppear(_ animated: Bool) {
- if userDefaults.bool(forKey: UserDefaultKeys.UserInfo.isLogin) {
- DispatchQueue.main.async { [self] in
- signInWithAppleButton.isHidden = true
- userInfoCell.setNickNameForCell(nickname: userDefaults.string(forKey: UserDefaultKeys.UserInfo.nickname))
- }
- }
- }
-
- func performExistingAccountSetupFlows() {
- if #available(iOS 13.0, *) {
- let request = [ASAuthorizationAppleIDProvider().createRequest(), ASAuthorizationPasswordProvider().createRequest()]
- let authorizationController = ASAuthorizationController(authorizationRequests: request)
- authorizationController.delegate = self
- authorizationController.presentationContextProvider = self
- authorizationController.performRequests()
- } else {
- // Fallback on earlier versions
- }
- }
-
- // @objc func renameAlert() {
- // let alertController = UIAlertController(title: "修改昵称", message: nil, preferredStyle: .alert)
- // let cancelAction = UIAlertAction(title: "取消", style: .cancel)
- // let confirmAction = UIAlertAction(title: "确定", style: .default, handler: { [self] action in
- // let textField = alertController.textFields![0]
- // changeNickName(userId: self.userDefault.string(forKey: UserDefaultKeys.UserInfo.userId)!, nickName: textField.text!) { [self] updatedNickName in
- // DispatchQueue.main.async { [self] in
- //// nickNameLabel.text = updatedNickName
- // }
- // userDefault.set(updatedNickName, forKey: UserDefaultKeys.UserInfo.nickname)
- // }
- //// self.nickNameLabel.text = textField.text
- // })
- // alertController.addTextField { (textField) in
- // textField.delegate = self
- // }
- // alertController.addAction(cancelAction)
- // alertController.addAction(confirmAction)
- // self.present(alertController, animated: true)
- // }
-
- @objc func handleAuthorizationAppleIDButtonPress() {
- let provider = ASAuthorizationAppleIDProvider()
- let request = provider.createRequest()
- request.requestedScopes = [.email, .fullName]
- let authorizationController = ASAuthorizationController(authorizationRequests: [request])
- authorizationController.delegate = self
- authorizationController.presentationContextProvider = self
- authorizationController.performRequests()
- }
-
- // func changeNickName(userId: String, nickName: String, complition: @escaping(_ updatedNickname: String) -> Void) {
- // let task = URLSession.shared.dataTask(with: netTools.get(url: "http://hefengyu.org:8080/user/changeNickname?", parameters: ["userId": userId, "nickname": nickName])) { (data, response, error) in
- // guard let unwrapedData = data else {
- // return
- // }
- // guard let updatedName = String(data: unwrapedData, encoding: .utf8) else {
- // return
- // }
- // print(updatedName)
- // if updatedName == nickName {
- // complition(updatedName)
- // } else {
- // complition(self.nickNameLabel.text!)
- // }
- // }
- // task.resume()
- // }
- }
- extension SettingsViewController: UITableViewDataSource, UITableViewDelegate {
-
- func numberOfSections(in tableView: UITableView) -> Int {
- return settingsSection
- }
-
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- switch section {
- case 0: return 1
- case 1: return 2
- case 2: return 1
- default: return 0
- }
- }
-
- func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
- return 20
- }
- // func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
- // <#code#>
- // }
- //
- func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
- switch indexPath.section {
- case 0: return 100
- case 1: return 44
- case 2: return 44
- default: return 44
- }
- }
- //每行对应的 Cell
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let identifier = "Cell"
- var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
-
- if cell == nil {
- cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
- }
-
- if indexPath.section == 0 {
- userInfoCell.setValueForCell(image: UIImage(named: "DefaultAvatar"), nickname: userDefaults.string(forKey: UserDefaultKeys.UserInfo.nickname))
- return userInfoCell
- } else if indexPath.section == 1 {
- cell?.textLabel!.text = headers[indexPath.row]
- cell?.textLabel?.textAlignment = .left
- } else if indexPath.section == 2 {
- cell?.textLabel?.text = "退出登录"
- cell?.textLabel?.textAlignment = .center
- }
- return cell!
- }
-
- func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
- if indexPath.section == 2 {
- let optionMenu = UIAlertController(title: nil, message: "退出登录?", preferredStyle: .actionSheet)
- let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { action in
- tableView.deselectRow(at: indexPath, animated: true)
- })
- let confirmAction = UIAlertAction(title: "确认", style: .default, handler: { [self] action in
- userDefaults.setValue(false, forKey: UserDefaultKeys.UserInfo.isLogin)
- userDefaults.setValue("", forKey: UserDefaultKeys.UserInfo.userId)
- userDefaults.setValue("", forKey: UserDefaultKeys.UserInfo.nickname)
- signInWithAppleButton.isHidden = false
- settingsSection = 2
- tableView.deselectRow(at: indexPath, animated: true)
- tableView.reloadData()
- })
- optionMenu.addAction(confirmAction)
- optionMenu.addAction(cancelAction)
- present(optionMenu, animated: true)
- }
- }
- }
- extension SettingsViewController: ASAuthorizationControllerDelegate {
- @available(iOS 13.0, *)
- func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
- //苹果用户唯一标识符,该值在同一个开发者账号下的所有 App 下是一样的,开发者可以用该唯一标识符与自己后台系统的账号体系绑定起来。
- if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
- let fullName = appleIDCredential.fullName
- var name = ""
- if let givenName = fullName?.givenName, let familyName = fullName?.familyName {
- name = "\(familyName) \(givenName)"
- }
- if name == "" {
- let identityToken = String(data: appleIDCredential.identityToken!, encoding: String.Encoding.utf8)!
- userLogin(appleToken: identityToken) { [self] isLogin, userId in
- if isLogin {
- findUserByAppleId(appleId: userId) { [self] nickname in
- userDefaults.set(nickname, forKey: UserDefaultKeys.UserInfo.nickname)
- DispatchQueue.main.async { [self] in
- settingsTableView.reloadSections(IndexSet(integer: 0), with: .none)
- }
- }
- userDefaults.set(userId, forKey: UserDefaultKeys.UserInfo.userId)
- userDefaults.set(isLogin, forKey: UserDefaultKeys.UserInfo.isLogin)
- DispatchQueue.main.async { [self] in
- signInWithAppleButton.isHidden = true
- userInfoCell.setNickNameForCell(nickname: userDefaults.string(forKey: UserDefaultKeys.UserInfo.nickname))
- settingsSection = 3
- settingsTableView.reloadData()
- }
- }
- }
- } else {
- let identityToken = String(data: appleIDCredential.identityToken!, encoding: String.Encoding.utf8)!
- userRegister(appleToken: identityToken, fullName: name) { [self] isLogin, userId in
- if isLogin {
- findUserByAppleId(appleId: userId) { [self] nickname in
- userDefaults.set(nickname, forKey: UserDefaultKeys.UserInfo.nickname)
- DispatchQueue.main.async { [self] in
- settingsTableView.reloadSections(IndexSet(integer: 0), with: .none)
- }
- }
- userDefaults.set(userId, forKey: UserDefaultKeys.UserInfo.userId)
- userDefaults.set(isLogin, forKey: UserDefaultKeys.UserInfo.isLogin)
- DispatchQueue.main.async { [self] in
- self.signInWithAppleButton.isHidden = true
- userInfoCell.setNickNameForCell(nickname: userDefaults.string(forKey: UserDefaultKeys.UserInfo.nickname))
- settingsSection = 3
- settingsTableView.reloadData()
- }
- }
- }
- }
- }
- }
-
- func userRegister(appleToken: String, fullName: String, complition: @escaping(_ isLogin: Bool, _ userId: String) -> Void) {
- let task = URLSession.shared.dataTask(with: netTools.get(url: APIs.Apple.Register, parameters: ["appleToken": appleToken, "fullName": fullName])) { (data, response, error) in
- guard let unwrapedData = data else {
- complition(false, "")
- return
- }
- guard let userId = String(data: unwrapedData, encoding: .utf8) else {
- complition(false, "")
- return
- }
- if userId == "-1" {
- complition(false, "")
- } else {
- complition(true, userId)
- }
- }
- task.resume()
- }
-
- func userLogin(appleToken: String, complition: @escaping(_ isLogin: Bool, _ userId: String) -> Void) {
- let task = URLSession.shared.dataTask(with: netTools.get(url: APIs.Apple.Login, parameters: ["appleToken": appleToken])) { (data, response, error) in
- guard let unwrapedData = data else {
- complition(false, "")
- return
- }
- guard let userId = String(data: unwrapedData, encoding: .utf8) else {
- complition(false, "")
- return
- }
- if userId == "-1" {
- complition(false, "")
- } else {
- complition(true, userId)
- }
- }
- task.resume()
- }
-
- func findUserByAppleId(appleId: String, complition: @escaping(_ nickname: String) -> Void) {
- let task = URLSession.shared.dataTask(with: netTools.get(url: APIs.User.FindUserByID, parameters: ["appleId": appleId])) { (data, response, error) in
- guard let unwrapedData = data else {
- return
- }
- guard let nickName = String(data: unwrapedData, encoding: .utf8) else {
- return
- }
- complition(nickName)
- }
- task.resume()
- }
-
- func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
- print("Login Error")
- }
- override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
- if #available(iOS 13, *) {
- if self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
- if self.traitCollection.userInterfaceStyle == .dark {
- // 黑夜模式
- view.backgroundColor = .black
- welcomeText.textColor = .white
- userIdLabel.textColor = .white
- } else {
- // 白天模式
- view.backgroundColor = .white
- welcomeText.textColor = .black
- userIdLabel.textColor = .black
- }
- }
- }
- }
- }
- extension SettingsViewController: ASAuthorizationControllerPresentationContextProviding {
- func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
- return self.view.window!
- }
- }
|