Anonymous Anonymous - 12 days ago
144 0

No description

Swift

asdfg

import UIKit
import FacebookCore
import FacebookLogin

class FacebookLoginViewController: BaseViewController, LoginButtonDelegate {

    var userEmail = ""
    
    @IBOutlet weak var backButton: UIButton!
    
    struct MyProfileRequest: GraphRequestProtocol {
        struct Response: GraphResponseProtocol {
            var name: String?
            var id: String?
            var gender: String?
            var email: String?
            var birthday: String?
            var profilePictureUrl: String?
            
            init(rawResponse: Any?) {
                // Decode JSON from rawResponse into other properties here.
                guard let response = rawResponse as? Dictionary<String, Any> else {
                    return
                }
                if let name = response["name"] as? String {
                    self.name = name
                }
                if let id = response["id"] as? String {
                    self.id = id
                }
                if let gender = response["gender"] as? String {
                    self.gender = gender
                }
                if let email = response["email"] as? String {
                    self.email = email
                }
                if let birthday = response["birthday"] as? String {
                    self.birthday = birthday
                }
                if let picture = response["picture"] as? Dictionary<String, Any> {
                    if let data = picture["data"] as? Dictionary<String, Any> {
                        if let url = data["url"] as? String {
                            self.profilePictureUrl = url
                        }
                    }
                }
            }
        }
        var graphPath = "/me"
        var parameters: [String : Any]? = ["fields": "name, gender, email, birthday, picture.type(large)"]
        var accessToken = AccessToken.current
        var httpMethod: GraphRequestHTTPMethod = .GET
        var apiVersion: GraphAPIVersion = .defaultVersion
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let loginButton = LoginButton(readPermissions: [ .publicProfile, .email, .userFriends ])
        
        loginButton.frame = CGRect(x: 0, y: 0, width: 230, height: 35)
        loginButton.center = view.center
        loginButton.delegate = self
        
        view.addSubview(loginButton)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        if let accessToken = AccessToken.current {
            print(accessToken)
            print("signed in fb")
            if (GlobalVar.currentFunc != "logout") {
                graphRequest()
            }
        }
    }
    
    func loginButtonDidCompleteLogin(_ loginButton: LoginButton, result: LoginResult) {
        print("user logged in fb")
        graphRequest()
    }
    
    func loginButtonDidLogOut(_ loginButton: LoginButton) {
        
        let fileManager = FileManager.default
        let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL
        let documentsPath = documentsUrl.path
        
        do {
            if let documentPath = documentsPath
            {
                let fileNames = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
                print("all files in doc: \(fileNames)")
                for fileName in fileNames {
                    
                    let filePathName = "\(documentPath)/\(fileName)"
                    try fileManager.removeItem(atPath: filePathName)
                }
                
                let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
                print("all files in doc after deleting: \(files)")
            }
        } catch {
            print("Could not clear folder: \(error)")
        }
        
        print("user logged out fb")
        dismiss(animated: true, completion: nil)
    }
    
    func graphRequest() {
        let connection = GraphRequestConnection()
        connection.add(MyProfileRequest()) { response, result in
            switch result {
            case .success(let response):
                self.userEmail = response.email!
                self.tryRegister(name: response.name, gender: response.gender, email: response.email, birthday: response.birthday, profilePictureUrl: response.profilePictureUrl)
            case .failed(let error):
                print("Custom Graph Request Failed: \(error)")
                self.displayAlertMessage(userMessage: "Cannot connect to facebook. Please try again later")
            }
        }
        connection.start()
    }
    
    func tryRegister(name: String?, gender: String?, email: String?, birthday: String?, profilePictureUrl: String?) {
        let requestURL = NSURL(string: GlobalVar.AuthDB)
        let request = NSMutableURLRequest(url: requestURL! as URL)
        request.httpMethod = "POST"
        
        let postParameters = "username=\(name!)&email=\(email!)&password=&full_name=\(name!)&gender=\(gender ?? "")&dob=\(birthday ?? "")&profilepic=\(profilePictureUrl ?? "")&register=facebook"
        request.httpBody = postParameters.data(using: String.Encoding.utf8)
        
        let task = URLSession.shared.dataTask(with: request as URLRequest){
            data, response, error in
            if error != nil{
                print(error ?? "unknown error")
                return
            }
            do {
                let string1 = String(data: data!, encoding: String.Encoding.utf8) ?? "Data could not be printed"
                print(string1)
                if(string1 == "Email exists." || string1 == "User successfully registered.") {
                    self.tryLogin(userEmail: email!)
                }
            }
        }
        task.resume()
    }
    
    func tryLogin(userEmail: String) { //email is in database
        let authURL = NSURL(string:GlobalVar.AuthDB)
        let request = NSMutableURLRequest(url: authURL! as URL)
        request.httpMethod = "POST"
        
        let postParameters = "email=\(userEmail)&password=&login=facebook"
        request.httpBody = postParameters.data(using: String.Encoding.utf8)
        
        let task = URLSession.shared.dataTask(with: request as URLRequest){
            data, response, error in
            if error != nil{
                print(error ?? "unknown error")
                return
            }
            do {
                guard let dataString = String(data: data!, encoding: String.Encoding.utf8) else {fatalError("Cannot string response")}
                if !dataString.hasPrefix("Error") {
                    let dataParsed = dataString.components(separatedBy: ";;")
                    UserDefaults.standard.set(dataParsed[0], forKey:"userId")
                    UserDefaults.standard.set(dataParsed[1], forKey:"username")
                    DispatchQueue.main.async {
                        UserDefaults.standard.set("facebook", forKey:"loginMode")
                        GlobalVar.currentFunc = "reloadApp"
                        self.dismiss(animated: true, completion: nil)
                    }
                } else {
                    print(dataString)
                    DispatchQueue.main.async {
                        self.displayAlertMessage(userMessage: "Cannot connect to server, please try again later.")
                    }
                }
            }
        }
        task.resume()
    }
    
    @IBAction func backButton(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
    
    func displayDismissMessage(userMessage:String) {
        let myAlert = UIAlertController(title: userMessage, message: "", preferredStyle: UIAlertControllerStyle.alert);
        
        let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler:{
            action -> Void in
            self.dismiss(animated: true, completion: nil)
        })
        
        myAlert.addAction(okAction)
        self.present(myAlert, animated:true, completion:nil)
    }
}