如何在单独的swift文件中进行域CRUD操作?

时间:2018-05-10 01:48:25

标签: ios swift realm

我是iOS开发和编程的初学者,我试图创建一个包含名为RealmService的域名CRUD操作的swift文件,所以我不必编写do catch块并尝试!遍布各地的领域,就像我的代码

import Foundation
import RealmSwift

class RealmService {

    var realm = try! Realm()

    func save(_ object: Object) {
        do {
            try realm.write {
                realm.add(object)
            }
        } catch {
            print("Failed to save \(object) in realm: \(error.localizedDescription)")
        }
    }

    func load(_ object: Object) -> Results<Object>? {
        return realm.objects(object.self)
    }

    func update(_ object: Object, with dictionary: [String: Any?]) {
        do {
            try realm.write {
                for (key, value) in dictionary {
                    object.setValue(value, forKey: key)
                }
            }
        } catch {
            print("Failed to update \(object) in realm: \(error.localizedDescription)")
        }
    }

    func delete(_ object: Object) {
        do {
            try realm.write {
                realm.delete(object)
            }
        } catch {
            print("Failed to delete \(object) in realm: \(error.localizedDescription)")
        }
    }
}

但在load方法中,我在行realm.objects(object.self)中收到错误,据说

  

无法将'Object'类型的值转换为预期的参数类型   'Object.Type'

enter image description here

我认为在realm.objects中插入object.self时会出错。它应该是element.type,但我不知道这个图片的元素类型是什么 enter image description here

如何从领域加载数据?遗憾的是,我只是通过使用realm.objects(object.self)

从youtube教程中了解一点

2 个答案:

答案 0 :(得分:2)

你正在做一个通过对象选择的工作,这是一个错误,因为它需要对象类型 package com.matt.dumate; import com.directions.route.AbstractRouting; import com.directions.route.Route; import com.directions.route.RouteException; import com.directions.route.Routing; import com.directions.route.RoutingListener; import com.firebase.geofire.GeoFire; import com.firebase.geofire.GeoLocation; import com.firebase.geofire.GeoQuery; import com.firebase.geofire.GeoQueryEventListener; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import android.Manifest; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class Welcome extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, RoutingListener{ SupportMapFragment mapFragment; private Button btnBooking; private Location lastLocation; private GoogleApiClient.OnConnectionFailedListener onConnectionFailedListener; private LocationRequest locationRequest; private LocationListener locationListener; private LocationManager locationManager; private Marker marker, driverMarker; private GoogleMap mMap; private GoogleApiClient googleApiClient; private final int RequestCode = 10; private final int ResourceCode = 11; private DatabaseReference userLastLocation, customersUnderServiceRef, userRequest, driversOnDuty,workingDrivers, driverRef1, driverWorkingRef ; GeoFire location, request, onDuty, customersUnderService; private Boolean clicked = false; private String driverID = ""; private ValueEventListener driverListener; private GeoQuery geoQuery; private String myId = ""; private Double driverLat, driverLng; @Override protected void onCreate(Bundle savedInstanceState) { checkLocationPermission(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); userLastLocation = FirebaseDatabase.getInstance().getReference("User LastLocation"); location = new GeoFire(userLastLocation); setupLocation(); userRequest = FirebaseDatabase.getInstance().getReference("User Request"); request = new GeoFire(userRequest); driversOnDuty = FirebaseDatabase.getInstance().getReference("DriversOnDuty"); onDuty = new GeoFire(driversOnDuty); driverRef1 = FirebaseDatabase.getInstance().getReference().child("Driver").child(driverID); driverWorkingRef = FirebaseDatabase.getInstance().getReference().child("DriversWorking"); customersUnderServiceRef = FirebaseDatabase.getInstance().getReference().child("CustomersUnderService"); customersUnderService = new GeoFire(customersUnderServiceRef); workingDrivers = FirebaseDatabase.getInstance().getReference().child("DriversWorking").child(driverID); } @Override public void onMapReady(GoogleMap googleMap) { myId = FirebaseAuth.getInstance().getCurrentUser().getUid(); setupUiViews(); mMap = googleMap; displayLocation(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case RequestCode: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (checkPlayServices()){ buildGoogleApiClient(); createLocationRequest(); displayLocation(); } } break; } } @Override public void onConnected(@Nullable Bundle bundle) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { locationRequest = LocationRequest .create() .setInterval(1000) .setFastestInterval(500) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); startLocationUpdates(); displayLocation(); }else { checkLocationPermission(); } } @Override public void onConnectionSuspended(int i) { googleApiClient.connect(); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onLocationChanged(Location location) { lastLocation = location; displayLocation2(); } public void checkLocationPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode); } } else { Toast.makeText(this, "Location Permissions Granted", Toast.LENGTH_SHORT).show(); } } protected synchronized void buildGoogleApiClient() { googleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); googleApiClient.connect(); } private void setupUiViews() { btnBooking = findViewById(R.id.bookingButton); btnBooking.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (clicked == false) { startLocationUpdates(); displayLocation2(); getNearestDriver(); Toast.makeText(Welcome.this, "Getting Cab", Toast.LENGTH_SHORT).show(); btnBooking.setText("Getting Your Cab.."); clicked = true; } else { disconnection(); try{ driverRef1.child("customerRideId").removeValue(); }catch (Exception a){ return; } stopLocationUpdates(); String userId = FirebaseAuth.getInstance().getCurrentUser().getUid(); DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference("Customer Request"); GeoFire geoFire1 = new GeoFire(databaseReference1); geoFire1.removeLocation(userId); Toast.makeText(Welcome.this, "Canceling Cab", Toast.LENGTH_SHORT).show(); btnBooking.setText("Get Cab"); if(driverMarker!=null){ driverMarker.remove(); } clicked = false; } } }); } private void displayLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); if (lastLocation != null ){ final Double lat = lastLocation.getLatitude(); final Double lng = lastLocation.getLongitude(); location.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(lat, lng), new GeoFire.CompletionListener() { @Override public void onComplete(String key, DatabaseError error) { if (marker != null) { marker.remove(); marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.locationmarker)).title("You")); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15.0f)); }else{ marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.locationmarker)).title("You")); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15.0f)); } } }); }else{ Log.d("Error", "Cannot Get Your Location"); } } private void displayLocation2() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); if (lastLocation != null ){ if(clicked == true){ final Double lat = lastLocation.getLatitude(); final Double lng = lastLocation.getLongitude(); request.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(lat, lng), new GeoFire.CompletionListener() { @Override public void onComplete(String key, DatabaseError error) { if (marker != null) { marker.remove(); marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.locationmarker)).title("You")); }else{ marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.locationmarker)).title("You")); } } }); } }else{ Log.d("Error", "Cannot Get Your Location"); } } private void setupLocation() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode); } }else{ if (checkPlayServices()) { buildGoogleApiClient(); createLocationRequest(); } } } private void createLocationRequest() { locationRequest = LocationRequest.create() .setInterval(1500) .setFastestInterval(500) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setSmallestDisplacement(0); } private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) GooglePlayServicesUtil.getErrorDialog(resultCode, this, ResourceCode).show(); else { Toast.makeText(this, "This Device Is Not Supported", Toast.LENGTH_SHORT).show(); finish(); }return false; } return true; } private void stopLocationUpdates() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this); } private void startLocationUpdates() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); } private int radius = 1; private Boolean driverFound = false; private void getNearestDriver() { geoQuery = location.queryAtLocation(new GeoLocation(lastLocation.getLatitude(), lastLocation.getLongitude()), radius); geoQuery.removeAllListeners(); geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() { @Override public void onKeyEntered(String key, GeoLocation location) { String driverId = key; if(!driverFound){ driverFound = true; driverID = key; DatabaseReference driverRef = FirebaseDatabase.getInstance().getReference().child("Driver").child(driverId); String customerId = FirebaseAuth.getInstance().getCurrentUser().getUid(); HashMap map = new HashMap(); map.put("customerRideId", customerId); driverRef.updateChildren(map); driverID = key; btnBooking.setText("Getting Driver Location"); customersUnderService.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(lastLocation.getLatitude(), lastLocation.getLongitude())); getDriverLocation(); } } @Override public void onKeyExited(String key) { disconnection(); } @Override public void onKeyMoved(String key, GeoLocation location) { } @Override public void onGeoQueryReady() { if(!driverFound){ radius++; getNearestDriver(); } } @Override public void onGeoQueryError(DatabaseError error) { disconnection(); Toast.makeText(Welcome.this, "GeoQuery Error", Toast.LENGTH_SHORT); } }); } private void getDriverLocation() { driverWorkingRef = driverWorkingRef.child(driverID).child("l"); driverListener = driverWorkingRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.exists()){ List<Object> map = (List<Object>) dataSnapshot.getValue(); double locationLat = 0; double locationLng = 0; btnBooking.setText("Driver Found"); if (map.get(0) != null) { locationLat = Double.parseDouble(map.get(0).toString()); driverLat = locationLat; } if (map.get(1) != null) { locationLng = Double.parseDouble(map.get(1).toString()); driverLng = locationLng; } LatLng driverLatLng = new LatLng(locationLat, locationLng); if (driverMarker != null) { driverMarker.remove(); } driverMarker = mMap.addMarker(new MarkerOptions().position(driverLatLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.carmarker)).title("You")); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(driverLatLng, 15.0f)); Location myLoc = new Location(""); Location driverLoc = new Location(""); myLoc.setLatitude(lastLocation.getLatitude()); myLoc.setLongitude(lastLocation.getLongitude()); driverLoc.setLatitude(locationLat); driverLoc.setLongitude(locationLng); float distance = myLoc.distanceTo(driverLoc); ; if (distance<100){ btnBooking.setText("Driver Reached"); }else{ btnBooking.setText("Driver at " + distance); } }getDriverLocation(); } @Override public void onCancelled(DatabaseError databaseError) { disconnection(); } }); } @Override public void onRoutingFailure(RouteException e) {} @Override public void onRoutingStart() {} @Override public void onRoutingSuccess(ArrayList<Route> arrayList, int i) {} @Override public void onRoutingCancelled() {} private void disconnection(){ try { customersUnderService.removeLocation(myId); }catch(Exception b){ } try { driverWorkingRef.removeEventListener(driverListener); }catch(Exception c){ } try { onDuty.setLocation(driverID,new GeoLocation(driverLat, driverLng)); }catch(Exception d){ } try { geoQuery.removeAllListeners(); }catch(Exception f){ } try { request.removeLocation(myId); }catch(Exception g){ } try { driverRef1.child("customerRideId").removeValue(); } catch(Exception h) { } try { onDuty.setLocation(driverID,new GeoLocation(driverLat, driverLng)); } catch(Exception h) { } driverFound = false; if (driverMarker != null){ driverMarker.remove(); } btnBooking.setText("Get Cab"); clicked = false; } @Override protected void onStop() { super.onStop(); //disconnection(); } private void getDirection(LatLng latLng) { Routing routing = new Routing.Builder() .travelMode(AbstractRouting.TravelMode.DRIVING) .withListener(this) .alternativeRoutes(true) .waypoints(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()), latLng) .build(); routing.execute(); } @Override protected void onPause() { super.onPause(); } } 而不是对象本身

尝试使用此

Element.Type

调用此函数

 func load<T: Object>(ofType: T.Type) -> Results<T> {

            return realm.objects(T.self)

    }

答案 1 :(得分:0)

我将ReamManager与CRUD结合使用是这样的:

mymap[2]

也许正是您想要的