Add events in Outlook Calendar swift 5

99封情书 提交于 2020-03-06 10:58:16

问题


I have fetching all the events now I want to add events in Outlook. can anyone help me on this that how can i add event in outlook. I am following this link for fetching: https://docs.microsoft.com/en-us/outlook/rest/ios-tutorial

There is not documentation for add events.

Please check this code.. this code works for getEmailAddress and getAllInbox. I check in SO not finding how can i add event. Please help! Thanks!!

import Foundation
import p2_OAuth2
import SwiftyJSON

class OutlookService {
    // Configure the OAuth2 framework for Azure
    private var userEmail: String

    private static let oauth2Settings = [
        "client_id" : "d765d128-6d36-4314-82f5-0b1efafc0100",
        "authorize_uri": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
        "token_uri": "https://login.microsoftonline.com/common/oauth2/v2.0/token",
        "scope": "openid profile offline_access User.Read Mail.Read Calendars.Read",
//        "scope": "openid profile offline_access User.Read Mail.Read",
        "redirect_uris": ["swift-tutorial://oauth2/callback"],
        "verbose": true,
        ] as OAuth2JSON

    private static var sharedService: OutlookService = {
        let service = OutlookService()
        return service
    }()

    private let oauth2: OAuth2CodeGrant

    private init() {
        oauth2 = OAuth2CodeGrant(settings: OutlookService.oauth2Settings)
        oauth2.authConfig.authorizeEmbedded = true
        userEmail = ""
    }

    class func shared() -> OutlookService {
        return sharedService
    }

    var isLoggedIn: Bool {
        get {
            return oauth2.hasUnexpiredAccessToken() || oauth2.refreshToken != nil
        }
    }

    func handleOAuthCallback(url: URL) -> Void {
        oauth2.handleRedirectURL(url)
    }

    func login(from: AnyObject, callback: @escaping (String? ) -> Void) -> Void {
        oauth2.authorizeEmbedded(from: from) {
            result, error in
            if let unwrappedError = error {
                callback(unwrappedError.description)
            } else {
                if let unwrappedResult = result, let token = unwrappedResult["access_token"] as? String {
                    // Print the access token to debug log
                    NSLog("Access token: \(token)")
                    callback(nil)
                }
            }
        }
    }

    func logout() -> Void {
        oauth2.forgetTokens()
    }

    func makeApiCall(api: String, params: [String: String]? = nil, callback: @escaping (JSON?) -> Void) -> Void {
        // Build the request URL
        var urlBuilder = URLComponents(string: "https://graph.microsoft.com")!
        urlBuilder.path = api

        if let unwrappedParams = params {
            // Add query parameters to URL
            urlBuilder.queryItems = [URLQueryItem]()
            for (paramName, paramValue) in unwrappedParams {
                urlBuilder.queryItems?.append(
                    URLQueryItem(name: paramName, value: paramValue))
            }
        }

        let apiUrl = urlBuilder.url!
        NSLog("Making request to \(apiUrl)")

        var req = oauth2.request(forURL: apiUrl)
        req.addValue("application/json", forHTTPHeaderField: "Accept")

        let loader = OAuth2DataLoader(oauth2: oauth2)

        // Uncomment this line to get verbose request/response info in
        // Xcode output window
        //loader.logger = OAuth2DebugLogger(.trace)

        loader.perform(request: req) {
            response in
            do {
                let dict = try response.responseJSON()
                DispatchQueue.main.async {
                    let result = JSON(dict)
                    callback(result)
                }
            }
            catch let error {
                DispatchQueue.main.async {
                    let result = JSON(error)
                    callback(result)
                }
            }
        }
    }

    func getUserEmail(callback: @escaping (String?) -> Void) -> Void {
        // If we don't have the user's email, get it from
        // the API
        if (userEmail.isEmpty) {
            makeApiCall(api: "/v1.0/me") {
                result in
                if let unwrappedResult = result {
                    var email = unwrappedResult["mail"].stringValue
                    if (email.isEmpty) {
                        // Fallback to userPrincipalName ONLY if mail is empty
                        email = unwrappedResult["userPrincipalName"].stringValue
                    }
                    self.userEmail = email
                    callback(email)
                } else {
                    callback(nil)
                }
            }
        } else {
            callback(userEmail)
        }
    }

    func getInboxMessages(callback: @escaping (JSON?) -> Void) -> Void {
        let apiParams = [
            "$select": "subject,receivedDateTime,from",
            "$orderby": "receivedDateTime DESC",
            "$top": "10"
        ]

        makeApiCall(api: "/v1.0/me/mailfolders/inbox/messages", params: apiParams) {
            result in
            callback(result)
        }
    }

    func getEvents(callback: @escaping (JSON?) -> Void) -> Void {
        let apiParams = [
            "$select": "subject,start,end",
            "$orderby": "start/dateTime ASC",
            "$top": "10"
        ]

        makeApiCall(api: "/v1.0/me/events", params: apiParams) {
            result in
            callback(result)
        }
    }

    func outlookDeepLink(subject: String, body: String, recipients: [String]) throws -> URL {

        enum MailComposeError: Error {
            case emptySubject
            case emptyBody
            case unexpectedError
        }

        guard !subject.isEmpty else { throw MailComposeError.emptySubject }
        guard !body.isEmpty else { throw MailComposeError.emptyBody }

        let emailTo = recipients.joined(separator: ";")

        var components = URLComponents()
        components.scheme = "ms-outlook"
        components.host = "compose"
        components.queryItems = [
            URLQueryItem(name: "to", value: emailTo),
            URLQueryItem(name: "subject", value: subject),
            URLQueryItem(name: "body", value: body),
        ]

        guard let deepURL = components.url else { throw MailComposeError.unexpectedError }
        return deepURL
    }
}

来源:https://stackoverflow.com/questions/60527754/add-events-in-outlook-calendar-swift-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!