Uploaded image for project: 'Documentation'
  1. Documentation
  2. DOCS-12034

Add code examples to Swift SDK README

    XMLWordPrintable

    Details

    • Type: Improvement
    • Status: Closed
    • Priority: Minor - P4
    • Resolution: Won't Fix
    • Affects Version/s: None
    • Fix Version/s: None
    • Component/s: Stitch
    • Labels:
    • # Replies:
      0
    • Last comment by Customer:
      true
    • Story Points:
      1

      Description

      Description

      As we discussed on Slack I'm just sending some sample code to potentially add to the GitHub readme for the swift sdk. The physical docs don't have examples, so I'm not sure if it is worth it to have some of the pages with example code and others without. However, some of this could certainly be added to the README.md to provide a few more complicated examples / walk through how to set it up in the project.

      At the top of every file put:
      import StitchCore
      import StitchRemoteMongoDBService
      (Do not think we need MongoSwiftMobile quite yet)

      1. Inside of AppDelegate.swift:

      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
      do

      { stitchClient = try Stitch.initializeAppClient(withClientAppID: "stitch_appid") }

      catch

      { print("Unable to connect to stitch client") }

      return true
      }

      2. To Login With Anonymous Credentials:

      stitchClient.auth.login(withCredential: AnonymousCredential()) {result in
      switch result {
      case .success(_):
      print("Stitch User ID: " + stitchClient.auth.currentUser!.id)
      DispatchQueue.main.async

      { // update UI accordingly }

      case .failure(let error):
      print("failed logging in Stitch with Facebook. error: (error)")
      }
      }

      3. To Login with another Credential (Facebook):

      // At The top of the page
      import FacebookLogin
      import FBSDKLoginKit
      import StitchCore

      // In viewDidLoad()
      let loginButton = LoginButton(readPermissions: [ .publicProfile, .email, .userFriends ])
      loginButton.center = view.center
      view.addSubview(loginButton)

      // In viewWillAppear() --> will call after Facebook successfully logs in
      if let accessToken = FBSDKAccessToken.current() {
      let credential = FacebookCredential.init(withAccessToken: accessToken.tokenString)
      stitchClient.auth.login(withCredential: credential) {result in
      switch result {
      case .success(_):
      print("Stitch User ID: " + stitchClient.auth.currentUser!.id)
      DispatchQueue.main.async

      { // update UI accordingly }

      case .failure(let error):
      print("failed logging in Stitch with Facebook. error: (error)")
      }
      }
      }

      4. Throughout the rest of the application, to get access to the defaultStitchClient just call:

      private lazy var stitchClient = Stitch.defaultAppClient!

      5. To Perform a Find:

      mongoClient = stitchClient.serviceClient(fromFactory: remoteMongoClientFactory, withName: "mongodb-atlas")
      collection = mongoClient?.db("db_name").collection("collection_name")
      collection.find(["filter_key": "filter_value"], options: RemoteFindOptions(limit: 3, sort: ["title": 1])).asArray({ result in
      switch result {
      case .success(let result):
      results.forEach({ document in
      guard let arr_of_sub_docs = doc["arrDocs"] as? [Document] else

      { print("Error: no array of subdocuments found") exit(0) }

      print(arr_of_sub_docs[0]["subdoc_field"])
      })

      case .failure(let error):
      print("Error in finding documents: (error)")
      }
      })

      6. Perform a Function Call:

      stitchClient.callFunction(withName: "insertFunctionName", withArgs: ["args"], withRequestTimeout: 5.0)
      {(result: StitchResult<String>) in
      switch result

      { case .success(let stringResult): print("String result: \(stringResult)") case .failure(let error): print("Error retrieving String: \(String(describing: error))") }

      }

      7. Insert a Document

      var newDoc = Document()
      newDoc["name"] = stitchClient.auth.currentUser?.profile.name! as! String
      newdoc["user_id"] = stitchClient.auth.currentUser!.id
      itemDoc["title"] = "newDocTitle"
      itemDoc["arrOfSubDocs"] = []
      self.groupCollection?.insertOne(itemDoc, {result in
      switch result

      { case .success(_): // Do Something case .failure(let error): print("failed logging out: \(error)") }

      })

      8. Update a Complicated Document (push a subdocument into an array):

      var newSubDoc = Document(["title": "newSubDocument"])
      var filterDoc = Document(["$push": Document(["arrOfSubDocs": newSubDoc])])
      collection.updateOne(
      filter: ["_id": subDoc["_id"] as! ObjectId],
      update: filterDoc,
      options: RemoteUpdateOptions(upsert: true),
      {result in
      switch result {
      case .success(_):
      DispatchQueue.main.async

      { // Update UI or perform transation }

      case .failure(let error):
      let alert = UIAlertController(title: "Update Failed", message: error.localizedDescription, preferredStyle: .alert)
      alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default,handler: nil))
      self.present(alert, animated: true)
      }
      }
      )

      Scope of changes

      Impact to Other Docs

      MVP (Work and Date)

      Resources (Scope or Design Docs, Invision, etc.)

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                chris.bush Chris Bush
                Reporter:
                tyler.kaye Tyler Kaye
                Participants:
                Last commenter:
                iwanfalls Iwanfall
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved:
                  Days since reply:
                  1 year, 19 weeks, 1 day ago