Last active
September 18, 2019 06:40
-
-
Save susanna2222/d62a41fce2d29bff6523b84dab0c2c82 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import Firebase | |
import FirebaseAuth | |
class ViewController: UIViewController { | |
var microsoftProvider : OAuthProvider? | |
let kGraphURI = "https://graph.microsoft.com/v1.0/me/" | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view. | |
self.microsoftProvider = OAuthProvider(providerID: "microsoft.com") | |
} | |
// the action when tap on Login by Office365 button | |
@IBAction func tapLoginByOffice365(_ sender: Any) { | |
self.microsoftProvider?.getCredentialWith(_: nil){credential, error in | |
if error != nil { | |
// Handle error. | |
} | |
if let credential = credential { | |
Auth.auth().signIn(with: credential) { (authResult, error) in | |
if error != nil { | |
// Handle error. | |
} | |
guard let authResult = authResult else { | |
print("Couldn't get graph authResult") | |
return | |
} | |
// get credential and token when login successfully | |
let microCredential = authResult.credential as! OAuthCredential | |
let token = microCredential.accessToken! | |
// use token to call Microsoft Graph API | |
self.getGraphContentWithToken(accessToken: token) | |
} | |
} | |
} | |
} | |
// function to call Microsoft Graph API by token | |
func getGraphContentWithToken(accessToken: String) { | |
// Specify the Graph API endpoint | |
let url = URL(string: kGraphURI) | |
var request = URLRequest(url: url!) | |
// Set the Authorization header for the request. We use Bearer tokens, so we specify Bearer + the token we got from the result | |
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") | |
URLSession.shared.dataTask(with: request) { data, response, error in | |
if let error = error { | |
print("Couldn't get graph result: \(error)") | |
return | |
} | |
guard let result = try? JSONSerialization.jsonObject(with: data!, options: []) else { | |
print("Couldn't deserialize result JSON") | |
return | |
} | |
print("Result from Graph: \(result))") | |
}.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment