2016-10-23 3 views
1

저는 iOS에서 상당히 새로워졌습니다. 사용자가 직장 주소를 변경할 때마다 Firebase에서 동료 노드를 업데이트하는 데 당분간 고생하고 있습니다. 논리는 매우 간단합니다. 누군가가 직장을 바꿀 때 그는 기존 동료 노드에서 제거하고 다른 노드로 옮겨야합니다.Swift를 사용하여 Firebase 테이블의 노드를 어떻게 업데이트 할 수 있습니까?

나는 주소의 첫 번째 변경 후 추가 노드를 얻을 아래 내가 기능을 실행할 때마다. 내 중포 기지 테이블처럼 보이게하는 방법

이입니다. 이 권리를 얻는 방법에 enter image description here

어떤 아이디어 나 생각?

func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) { 
    print("Place name: ", place.name) 
    print("Place address: ", place.formattedAddress) 
    print("Place attributions: ", place.attributions) 
    self.placeName.text = place.name + ", " + place.formattedAddress! 

    // grab workplace values to be updated in Firebase 
    // check for duplicates 
    let placeName : String = place.name 
    let placeAddress : String = place.formattedAddress! 
    let workplaceData = ["place_address":placeAddress,"place_name":placeName] 


    /* COLLEAGUES */ 
    // grab my current workplace id and remove me from the list 

    self.prRef.child(self.getUid()) 
     .observe(.value, with : { (snapshot: FIRDataSnapshot) in 
      // check if this is the same with the one just entered 
      let profilesDict = snapshot.value as? [String : AnyObject] 
      let workplaceID = (profilesDict?["workplace_id"] as! String) 
      self.currentWorkplaceId = workplaceID 
      print("the current - inside - workplace_id: \(self.currentWorkplaceId)") 
    }) 
    print("the current workplace_id: \(self.currentWorkplaceId)") 
    self.collRef.child("\(self.currentWorkplaceId)/\(self.getUid())").removeValue() 
    /* end updating workplace for a new, non-existent address in workplaces */ 

    /* WORKPLACE 
    - check for existent worklace formatted address and grab ID 
    - create new workplace if doesn't exist, based on a pre-generated ID 
    */ 
    wkRef 
     .queryOrdered(byChild: "place_address") 
     .queryEqual(toValue: placeAddress) 
     .observe(.value, with : { (snapshot: FIRDataSnapshot) in 
      //print("workplace query: \(snapshot)") 

      if (snapshot.value is NSNull) { 
       //print("Address was not found, we have to create it") 

       // update workplaces 
       let newWorkplaceUpdate = self.db.WKPLACES_REF.childByAutoId() 
       self.newWorkPlaceKey = newWorkplaceUpdate.key // get workplace id key 

       print("new address, new workplace key: \(self.newWorkPlaceKey)") 
       let updateWorkplaceData = ["\(self.newWorkPlaceKey)":workplaceData] 
       self.wkRef.updateChildValues(updateWorkplaceData) 

      } else { //in case a new address is an existent address 

       // take the existent key from workplaces 
       for child in snapshot.children { 
        self.newWorkPlaceKey = (child as AnyObject).key as String 
       } 
       print("workplace key exists, and is : \(self.newWorkPlaceKey)") 

       //newWorkPlaceId = key//remove 
       //print("existent workplace id: \(newWorkPlaceId)")//remove 
      } 
      // update profiles 
      let profRef = self.prRef.child(self.getUid()) 
      let updateWorkplaceProfileData = ["workplace_id": self.newWorkPlaceKey, "place_address":placeAddress,"place_name":placeName] 
      profRef.updateChildValues(updateWorkplaceProfileData) 

      // update colleagues 
      self.prRef.child(self.getUid()).observe(.value, with : { (snapshot) in 
       let profilesDict = snapshot.value as? [String : AnyObject] 
       //print(profilesDict) 
       self.collValues = [ 
        "full_name":(profilesDict?["full_name"])!, 
        "mobile":(profilesDict?["mobile"])!, 
        "avatar":(profilesDict?["avatar"])!, 
        "role": (profilesDict?["role"])! 
       ] 
       let colleaguesRef = self.collRef.child("\(self.newWorkPlaceKey)") 
       let colleaguesData = ["\(self.getUid())": self.collValues] 
       colleaguesRef.updateChildValues(colleaguesData) 
      }) 
    }) 



    self.dismiss(animated: true, completion: nil) 
} 

답변

1

문제는, 만든 중포 기지에 대한 호출이 비동기, 그래서 그것은 당신의 값이 검색도 전에 중포 기지에서 값을 검색하는 데 시간이 걸리지 만이다

print("the current - inside - workplace_id: \(currentWorkplaceId)") 

이 실행됩니다.

PS : -가 ..... 당신이하는 TimeInterval이 추가 타이머를 사용하는 함수 내에서 전역 변수에 대한 인쇄 문을 넣어 당신이 볼 수

+0

덕분에이를 확인하려면 @Dravidian I 기능 안에서 작동한다는 것을 알았습니다. 이 질문의 이유는 Firebase에서 몇 가지 관계형 테이블을 쿼리하고 사용자 액션에 따라 값을 모두 업데이트하는 문제입니다. 어쩌면 나는 더 나은 접근법이 될 수 있는지 여기에서 전체 문제점을 게시해야합니다. – Rob

+0

정확히 무엇을하고 싶은지 간략하게 설명 할 수 있습니까/ – Dravidian

+0

주소를 변경할 때마다 동료 테이블에서 현재 사용자 ID (로그인 한 사용자)를 제거하고 싶습니다. (주소를 자동 완성하기 위해 Google 지역 정보를 구현했습니다.) – Rob

관련 문제