微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使 ParseServer 与 ParseSwift 一起工作

如何解决如何使 ParseServer 与 ParseSwift 一起工作

我有一个使用 SwiftUI 的 iOS 应用。 然后利用 ParseSwift,我试图让它与 Parse-Server 一起工作。由于某些原因,事情没有解决。如果有人能对这个问题有所了解,那将非常有帮助。

首先,这是服务器的代码

const express = require('express');
const ParseServer = require('parse-server').ParseServer;
const path = require('path');
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
const args = process.argv || [];
const test = args.some(arg => arg.includes('jasmine'));

const databaseUri = process.env.MONGODB_URI;

if (!databaseUri) {
  console.log('DATABASE_URI not specified,falling back to localhost.');
}

const config = {
  databaseURI: databaseUri,cloud: __dirname + '/cloud/main.js',appId: process.env.APP_ID,masterKey: process.env.MASTER_KEY,serverURL: process.env.SERVER_URL,publicServerURL: process.env.PARSE_PUBLIC_SERVER_URL,liveQuery: {
    classNames: ['SampleCollection','MainCollection'],},};

const app = express();

// Serve static assets from the /public folder
app.use('/public',express.static(path.join(__dirname,'/public')));
app.set('port',(process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.set('views',__dirname + '/views');
app.set('view engine','ejs');

// Serve the Parse API on the /parse URL prefix
const mountPath = '/parse';

if (!test) {
  const api = new ParseServer(config);
  app.use(mountPath,api);
}

// Parse Server plays nicely with the rest of your web routes
app.get('/',function (req,res) {
  topdisplayFunc("index",res);
});

// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test',res) {
  res.sendFile(path.join(__dirname,'/public/test.html'));
});

const port = process.env.PORT || 1337;
if (!test) {
  const httpServer = require('http').createServer(app);
  httpServer.listen(port,function () {
    console.log('parse-server-example running on port ' + port + '.');
  });
  // This will enable the Live Query real-time server
  ParseServer.createLiveQueryServer(httpServer);
}

module.exports = {
  app,config,};


function topdisplayFunc(displayPage,response) {
  MongoClient.connect(databaseUri,{useUnifiedTopology: true},function(err,client) {
    if (err) throw err;

    var db = client.db();
    
    let theCollection = db.collection('SampleCollection');
    theCollection.countDocuments().then((count) => {
        theCollection.insertOne({number: count + 1},function (err) {
          if(err) throw err;

          db.collection('SampleCollection',function (err,collection) {
            collection.find().toArray(function(err,items) {
              if(err) throw err;
      
              response.render('pages/' + displayPage,{
                dataArray: items
              });
      
              client.close();
            });
          });
        });
    });
  });
}

以下是iOS应用中的相关代码

func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    .......
    ParseSwift.initialize(applicationId: parseAppId,clientKey: parseKey,serverURL: URL(string: parseServer)!)
    
    return true
}

然后:

//  ContentView.swift

import SwiftUI
import CoreData
import ParseSwift


.......
var onlineQuery = SampleCollection.query(["number" > 5])

struct ContentView: View {
    @Environment(\.managedobjectContext) var managedobjectContext
    .......

    var body: some View {
        .......
        ZStack{}.sheet(isPresented: $showingOnLine) {
            OnLineView()
                //.environmentObject(langType)
        }
    }
}

最后是视图的代码,当我在与 SampleCollection 相关的服务器上执行一些操作时,我希望发生某些事情,但没有任何反应。

import SwiftUI
import ParseSwift

struct OnLineView: View {
    @Observedobject var subscription = onlineQuery.subscribe!
    
    var body: some View {
        vstack {
            if subscription.subscribed != nil {
                Text("Subscribed to query!")
            } else if subscription.unsubscribed != nil {
                Text("Unsubscribed from query!")
            } else if let event = subscription.event {

                //: This is how you register to receive notifications of events related to your LiveQuery.
                switch event.event {

                case .entered(let object):
                    Text("Entered EVENT: ")
                case .left(let object):
                    Text("Left EVENT: ")
                case .created(let object):
                    Text("Created EVENT: ")
                case .updated(let object):
                    Text("Updated EVENT: ")
                case .deleted(let object):
                    Text("Deleted EVENT: ")
                default:
                    Text("Default-event !!!!")
                }
            } else {
                Text("Not subscribed to a query")
            }

            Spacer()

            Text("Update DATA in Parse Dashboard to see changes here")

            Button(action: {
                try? onlineQuery.unsubscribe()
            },label: {
                Text("Unsubscribe")
                    .font(.headline)
                    .background(Color.red)
                    .foregroundColor(.white)
                    .padding()
                    .cornerRadius(20.0)
                    .frame(width: 300,height: 50)
            })
        }
    }
}

struct OnLineView_Previews: PreviewProvider {
    static var previews: some View {
        OnLineView()
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。