Skip to content

Commit

Permalink
170829 - user singleton 처리 및 구글 로그인 시 오류 해결 #207
Browse files Browse the repository at this point in the history
  • Loading branch information
JuneBuug committed Aug 29, 2017
1 parent f0073a6 commit f39678f
Show file tree
Hide file tree
Showing 14 changed files with 91 additions and 89 deletions.
30 changes: 17 additions & 13 deletions iOSProject/pyunrihae/pyunrihae/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import GoogleSignIn
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,GIDSignInDelegate{
var window: UIWindow?
var user: User?
var productList : [Product] = []
let category = ["전체","도시락","김밥","베이커리","라면","식품","스낵","아이스크림","음료"]
let priceLevelList = ["비싸다","비싼편","적당","싼편","싸다"]
Expand All @@ -25,11 +24,11 @@ class AppDelegate: UIResponder, UIApplicationDelegate,GIDSignInDelegate{
GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
GIDSignIn.sharedInstance().delegate = self

let handle = Auth.auth().addStateDidChangeListener { (auth, user) in
_ = Auth.auth().addStateDidChangeListener { (auth, user) in
if user == nil {
do {
try Auth.auth().signOut()
self.user = User.init()
User.sharedInstance = User.init()
NotificationCenter.default.post(name: NSNotification.Name("userLogined"), object: nil)
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
Expand All @@ -38,7 +37,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate,GIDSignInDelegate{
}

// 오프라인 일 때 기기에 저장
Database.database().isPersistenceEnabled = true
// Database.database().isPersistenceEnabled = true
return true
}
func applicationWillResignActive(_ application: UIApplication) {
Expand Down Expand Up @@ -80,17 +79,22 @@ class AppDelegate: UIResponder, UIApplicationDelegate,GIDSignInDelegate{
// ...

Auth.auth().signIn(with: credential) { (user, error) in
if let error = error {
// ...
if error != nil {
// 에러 발생하면
return
}
// User is signed in
// ...

let user_instance = User.init(id: (user?.uid)!, email: (user?.email)!, nickname: (user?.displayName)!)
DataManager.saveUser(user: user_instance)
self.user = user_instance
NotificationCenter.default.post(name: NSNotification.Name("userLogined"), object: nil)
DataManager.getUserFromUID(uid: (user?.uid)!, completion: { (resultUser) in
if resultUser.email != "" { // 이전에 연결된 게 있으면
User.sharedInstance = resultUser
NotificationCenter.default.post(name: NSNotification.Name("userLogined"), object: nil)
}else{ // 새로 가입한 거라면
let user_instance = User.init(id: (user!.uid), email: (user?.email)!, nickname: (user?.displayName)!)
DataManager.saveUser(user: user_instance)
}
})


}

}
Expand All @@ -103,7 +107,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate,GIDSignInDelegate{
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
self.user = User.init()
User.sharedInstance = User.init()
NotificationCenter.default.post(name: NSNotification.Name("userLogined"), object: nil)
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
Expand Down
35 changes: 17 additions & 18 deletions iOSProject/pyunrihae/pyunrihae/Button.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

//
// Button.swift
// pyunrihae
Expand Down Expand Up @@ -93,14 +94,13 @@ class Button{
return categoryBtns
}
static func didPressUsefulBtn(sender: UIButton, reviewId: String, usefulNumLabel: UILabel, badNumLabel: UILabel, usefulBtn: UIButton, badBtn: UIButton, reviewList: [Review]){
let appdelegate = UIApplication.shared.delegate as! AppDelegate
var reviewStatus = appdelegate.user?.review_like_list[reviewId]
let uid = appdelegate.user?.id
var reviewStatus = User.sharedInstance.review_like_list[reviewId]
let uid = User.sharedInstance.id
if reviewStatus == nil { //유용해요 누른적이 없는 리뷰
var useful = Int(usefulNumLabel.text!)
useful = useful! + 1
usefulNumLabel.text = String(describing: useful!)
DataManager.updateUsefulReview(id: reviewId, uid: uid!)
DataManager.updateUsefulReview(id: reviewId, uid: uid)
reviewStatus = 1
Button.makeBorder(btn: usefulBtn)
Button.deleteBorder(btn: badBtn)
Expand All @@ -110,7 +110,7 @@ class Button{
var useful = Int(usefulNumLabel.text!)
useful = useful! - 1
usefulNumLabel.text = String(describing: useful!)
DataManager.updateCancleReview(id: reviewId, uid: uid!)
DataManager.updateCancleReview(id: reviewId, uid: uid)
reviewStatus = 0
Button.deleteBorder(btn: usefulBtn)
Button.deleteBorder(btn: badBtn)
Expand All @@ -123,7 +123,7 @@ class Button{
var bad = Int(badNumLabel.text!)
bad = bad! - 1
badNumLabel.text = String(describing: bad!)
DataManager.updateUsefulReview(id: reviewId, uid: uid!)
DataManager.updateUsefulReview(id: reviewId, uid: uid)
reviewStatus = 1
Button.makeBorder(btn: usefulBtn)
Button.deleteBorder(btn: badBtn)
Expand All @@ -133,14 +133,14 @@ class Button{
var useful = Int(usefulNumLabel.text!)
useful = useful! + 1
usefulNumLabel.text = String(describing: useful!)
DataManager.updateUsefulReview(id: reviewId, uid: uid!)
DataManager.updateUsefulReview(id: reviewId, uid: uid)
reviewStatus = 1
Button.makeBorder(btn: usefulBtn)
Button.deleteBorder(btn: badBtn)
usefulNumLabel.textColor = UIColor.red
badNumLabel.textColor = UIColor.lightGray
}
appdelegate.user?.review_like_list[reviewId] = reviewStatus
User.sharedInstance.review_like_list[reviewId] = reviewStatus
for i in 0..<reviewList.count {
if reviewList[i].id == reviewId {
reviewList[i].useful = Int(usefulNumLabel.text!)!
Expand All @@ -151,14 +151,13 @@ class Button{
}
}
static func didPressBadBtn(sender: UIButton, reviewId: String, usefulNumLabel: UILabel, badNumLabel: UILabel, usefulBtn: UIButton, badBtn: UIButton, reviewList: [Review]){
let appdelegate = UIApplication.shared.delegate as! AppDelegate
let uid = appdelegate.user?.id
var reviewStatus = appdelegate.user?.review_like_list[reviewId]
let uid = User.sharedInstance.id
var reviewStatus = User.sharedInstance.review_like_list[reviewId]
if reviewStatus == nil { //별로에요 누른적이 없는 리뷰
var bad = Int(badNumLabel.text!)
bad = bad! + 1
badNumLabel.text = String(describing: bad!)
DataManager.updateBadReview(id: reviewId, uid: uid!)
DataManager.updateBadReview(id: reviewId, uid: uid)
reviewStatus = -1
Button.makeBorder(btn: badBtn)
Button.deleteBorder(btn: usefulBtn)
Expand All @@ -168,7 +167,7 @@ class Button{
var bad = Int(badNumLabel.text!)
bad = bad! - 1
badNumLabel.text = String(describing: bad!)
DataManager.updateCancleReview(id: reviewId, uid: uid!)
DataManager.updateCancleReview(id: reviewId, uid: uid)
reviewStatus = 0
Button.deleteBorder(btn: usefulBtn)
Button.deleteBorder(btn: badBtn)
Expand All @@ -181,7 +180,7 @@ class Button{
var useful = Int(usefulNumLabel.text!)
useful = useful! - 1
usefulNumLabel.text = String(describing: useful!)
DataManager.updateBadReview(id: reviewId, uid: uid!)
DataManager.updateBadReview(id: reviewId, uid: uid)
reviewStatus = -1
Button.makeBorder(btn: badBtn)
Button.deleteBorder(btn: usefulBtn)
Expand All @@ -191,14 +190,14 @@ class Button{
var bad = Int(badNumLabel.text!)
bad = bad! + 1
badNumLabel.text = String(describing: bad!)
DataManager.updateBadReview(id: reviewId, uid: uid!)
DataManager.updateBadReview(id: reviewId, uid: uid)
reviewStatus = -1
Button.makeBorder(btn: badBtn)
Button.deleteBorder(btn: usefulBtn)
usefulNumLabel.textColor = UIColor.lightGray
badNumLabel.textColor = UIColor.red
}
appdelegate.user?.review_like_list[reviewId] = reviewStatus
User.sharedInstance.review_like_list[reviewId] = reviewStatus
for i in 0..<reviewList.count {
if reviewList[i].id == reviewId {
reviewList[i].useful = Int(usefulNumLabel.text!)!
Expand All @@ -209,8 +208,8 @@ class Button{
}
}
static func validateUseful(review: Review, usefulBtn: UIButton, badBtn: UIButton, usefulNumLabel: UILabel, badNumLabel: UILabel) {
let appdelegate = UIApplication.shared.delegate as! AppDelegate
if let userReviewLike = appdelegate.user?.review_like_list[review.id]{

if let userReviewLike = User.sharedInstance.review_like_list[review.id]{
if userReviewLike == 1 {
Button.makeBorder(btn: usefulBtn)
Button.deleteBorder(btn: badBtn)
Expand Down
11 changes: 6 additions & 5 deletions iOSProject/pyunrihae/pyunrihae/DataManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -202,8 +202,7 @@ class DataManager{
update["wish_product_list"] = wishList
}
localRef.updateChildValues(update)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.user?.wish_product_list = wishList
User.sharedInstance.wish_product_list = wishList
NotificationCenter.default.post(name: NSNotification.Name("likeListChanged"), object: nil)
})
}
Expand Down Expand Up @@ -452,12 +451,13 @@ class DataManager{
if let data = UIImageJPEGRepresentation(p_image, 0.3) {
imagesRef.putData(data, metadata: nil, completion: {
(metadata, error) in
if error != nil {
if error != nil { // 에러가 난 경우
update["p_image"] = imgURL
id.updateChildValues(update)
NotificationCenter.default.post(name: NSNotification.Name("reviewUpload"), object: self)
NotificationCenter.default.post(name: NSNotification.Name("complete"), object: self)
} else {
// 정상 작동한 경우
imagesRef.downloadURL { (URL, error) -> Void in // 업로드된 이미지 url 받아오기
if (error != nil) { // 없으면 ""로 저장
update["p_image"] = imgURL
Expand All @@ -474,7 +474,7 @@ class DataManager{
}
}
})
} else {
} else { // 이미지가 없는 경우
update["p_image"] = imgURL
id.updateChildValues(update)
NotificationCenter.default.post(name: NSNotification.Name("reviewUpload"), object: self)
Expand Down Expand Up @@ -528,6 +528,7 @@ class DataManager{
let localRef = ref.child("user")
localRef.child(user.id).setValue(["id": user.id, "email" : user.email, "nickname" : user.nickname, "review_like_list": user.review_like_list, "product_review_list" : user.product_review_list, "wish_product_list": user.wish_product_list])
}


/*
* 마이페이지 화면
Expand Down Expand Up @@ -596,7 +597,7 @@ class DataManager{
contentBuilder.desc = review.comment


if review.product_image != nil && review.product_image != "" {
if review.product_image != "" {
contentBuilder.imageURL = URL.init(string : review.product_image)!
}else{
contentBuilder.imageURL = URL.init(string : "https://s3.ap-northeast-2.amazonaws.com/pyunrihae/Group%402x.png")!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ class LikeProductViewController: UIViewController {
}
func getLikeProductList(){
likeProductList = []
if (appdelegate.user?.wish_product_list)! != [] && appdelegate.user?.wish_product_list != nil{
if (User.sharedInstance.wish_product_list) != [] {
for product in appdelegate.productList {
for id in (appdelegate.user?.wish_product_list)! {
for id in (User.sharedInstance.wish_product_list) {
if product.id == id {
likeProductList.append(product)
}
Expand Down
6 changes: 3 additions & 3 deletions iOSProject/pyunrihae/pyunrihae/LoginViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,16 @@ class LoginViewController: UIViewController {
self.alertLabel.alpha = 0
})
}else{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
_ = UIApplication.shared.delegate as! AppDelegate
if Auth.auth().currentUser != nil {
DataManager.getUserFromUID(uid: (Auth.auth().currentUser?.uid)!, completion: { (user) in
appDelegate.user = user
User.sharedInstance = user
self.dismiss(animated: true, completion: {
NotificationCenter.default.post(name: NSNotification.Name("userLogined"), object: nil)
})
})
} else {
appDelegate.user = User()
User.sharedInstance = User()
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions iOSProject/pyunrihae/pyunrihae/MainViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ class MainViewController: UIViewController {
}
}
func didPressUsefulBtn(sender: UIButton) { //유용해요 버튼 누르기
if appdelegate.user?.email == "" {
if User.sharedInstance.email == "" {
let alert = UIAlertController(title: "로그인 후 이용해주세요!", message: "", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
Expand All @@ -346,7 +346,7 @@ class MainViewController: UIViewController {
}
}
func didPressBadBtn(sender: UIButton) { //별로에요 버튼 누르기
if appdelegate.user?.email == "" {
if User.sharedInstance.email == "" {
let alert = UIAlertController(title: "로그인 후 이용해주세요!", message: "", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
Expand Down
32 changes: 15 additions & 17 deletions iOSProject/pyunrihae/pyunrihae/MypageViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,12 @@ class MypageViewController: UIViewController, FusumaDelegate{
}
}
func checkUserLogin(){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let user = appDelegate.user
if user?.email != "" {
if user?.user_profile != nil {
let user = User.sharedInstance
if user.email != "" {
if user.user_profile != "" {
// userImage.af_setImage(withURL: URL(string: (user?.user_profile)!)!)
// userImage.image = userImage.image?.af_imageRoundedIntoCircle()
let url = URL(string: (user?.user_profile)!)!
let url = URL(string: (user.user_profile))!
let placeholderImage = UIImage(named: "ic_user")!
let filter = AspectScaledToFillSizeCircleFilter(
size: userImage.frame.size
Expand All @@ -64,8 +63,8 @@ class MypageViewController: UIViewController, FusumaDelegate{
}else{
userImage.image = UIImage(named: "user_default.png")
}
nickNameLabel.text = user?.nickname
emailLabel.text = user?.email
nickNameLabel.text = user.nickname
emailLabel.text = user.email
labelList[2] = "로그아웃"
DispatchQueue.main.async {
self.moreImg.isHidden = false
Expand All @@ -84,12 +83,11 @@ class MypageViewController: UIViewController, FusumaDelegate{
}
}
func setLogined(){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let currentUser = appDelegate.user
if currentUser?.email != "" {
let currentUser = User.sharedInstance
if currentUser.email != "" {
DispatchQueue.main.async{
self.nickNameLabel.text = currentUser?.nickname
self.emailLabel.text = currentUser?.email
self.nickNameLabel.text = currentUser.nickname
self.emailLabel.text = currentUser.email
self.labelList[2] = "로그아웃"
self.tableView.reloadData()
}
Expand Down Expand Up @@ -127,7 +125,7 @@ class MypageViewController: UIViewController, FusumaDelegate{
}
}
func profileTapped(){
if appDelegate.user?.email != "" {
if User.sharedInstance.email != "" {
let fusuma = FusumaViewController()
fusuma.delegate = self
fusuma.cropHeightRatio = 0.7
Expand All @@ -138,10 +136,10 @@ class MypageViewController: UIViewController, FusumaDelegate{
}
}
func fusumaImageSelected(_ image: UIImage, source: FusumaMode) {
if appDelegate.user?.email != "" {
if User.sharedInstance.email != "" {
userImage.image = image
userImage.image = userImage.image?.af_imageRoundedIntoCircle()
DataManager.updateUserProfile(user: appDelegate.user!, profile: image)
DataManager.updateUserProfile(user: User.sharedInstance, profile: image)
}
}
func fusumaMultipleImageSelected(_ images: [UIImage], source: FusumaMode) {
Expand Down Expand Up @@ -183,7 +181,7 @@ extension MypageViewController: UITableViewDataSource, UITableViewDelegate {
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 { // 내가 찜한 상품을 눌렀을 때
if appDelegate.user?.email == "" { // 로그인 된 상태가 아니면
if User.sharedInstance.email == "" { // 로그인 된 상태가 아니면
let alertController = UIAlertController(title: "알림", message: "내가 찜한 상품은 로그인 뒤 이용가능합니다.", preferredStyle: UIAlertControllerStyle.alert)
let DestructiveAction = UIAlertAction(title: "취소", style: UIAlertActionStyle.destructive) { (result : UIAlertAction) -> Void in
alertController.dismiss(animated: false, completion: nil)
Expand Down Expand Up @@ -220,7 +218,7 @@ extension MypageViewController: UITableViewDataSource, UITableViewDelegate {
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
self.appDelegate.user = User()
User.sharedInstance = User()
self.setLogined()
self.showAlertIfLogined(bool: false)
} catch let signOutError as NSError {
Expand Down
Loading

0 comments on commit f39678f

Please sign in to comment.