Как вы настраиваете свои правила хранения, чтобы соответствовать вашему приложению? - PullRequest
0 голосов
/ 12 января 2020

Предпосылка: Эти правила в настоящее время

       rules_version = '2';
   service firebase.storage {
 match /b/{bucket}/o {
   match /{allPaths=**} {
     allow read, write: if request.auth != null;
   }
 }
}

Когда я запускаю вышеуказанные правила, отображается не все изображение пользователя. Я не знаю, так ли это, потому что все пользователи подключены к одному телефону (я провожу тестирование самостоятельно, выхожу из системы и захожу, промываю и повторяю), но я сомневаюсь в этом. В этих правилах есть нечто (в частности, auth! Not nil part), которое заставляет возвращать не все изображения. Я говорю это потому, что с нижеследующим правилом каждый пользователь получает изображение (хотя и не всегда то, которое он загрузил, потому что правила разрешают все, но, тем не менее, он показывает, что код может извлекать изображения всем пользователям из firebase).

     rules_version = '2';
    service firebase.storage {
   match /b/{bucket}/o {
     match /{allPaths=**} {
      allow read, write;
    }
 }
 }

Вот код для извлечения изображений из базы данных.

class homepage: UITableViewController, CLLocationManagerDelegate{

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])   {
    let databaseRef = Database.database().reference()
    let uid = Auth.auth().currentUser!.uid
    guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
    print("locations = \(locValue.latitude) \(locValue.longitude)")
    latestLocation = ["latitude" : locValue.latitude, "longitude" : locValue.longitude]
    let lat = locValue.latitude
    let lon = locValue.longitude
    dict = CLLocation(latitude: lat, longitude: lon)
    print("dict", dict)
    if let locationDictionary = latestLocation {       databaseRef.child("people").child(uid).child("Coordinates").setValue(locationDictionary)   
    }  
}

.....

public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return people.count
}

public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell
    let immy = cell.viewWithTag(1) as! UIImageView
    let person: Userx = people[indexPath.row]
    let like = cell.viewWithTag(3) as! UIButton
    cell.lblName.text = person.Education
    cell.postID = self.people[indexPath.row].postID
    if let PhotoPosts = person.PhotoPosts {
        let url = URL(string: PhotoPosts)
        immy.sd_setImage(with: url)
    }
    return cell
}

......

  override func viewDidLoad() {
    super.viewDidLoad()
    table.dataSource = self
    table.delegate = self
   ........      
        if snapshot.childrenCount>0{
            self.people.removeAll()
            for people in snapshot.children.allObjects as! [DataSnapshot] {   
                    if people.key != thisUsersUid {
                        print("peoplekey",people.key)
                    let peoplePhotoPosts = peopleObject?["PhotoPosts"]  as? String
                    let peopleimageDownloadURL = peopleObject?["imageDownloadURL"]  as? String

                            let peopl = Userx(............PhotoPosts: peoplePhotoPosts, imageDownloadURL: peopleimageDownloadURL, postID: peoplepostID, .........)

                    self.people.append(peopl)

                        } else {
                            print ("145454")
                        }
                                    } else {
                                                                                                   print ("alphaaa")                                                                                                                                       
                     }

}
            self.people.sort { ($0.distance ?? 0) < ($1.distance ?? 0) 
}
                                  print("aaaaaaaa", self.people.map {$0.distance})        
                                  self.table.reloadData()
            }
        }     
    })

....

extension UIImageView {
public func imageFromServerURL(urlString: String) {
    self.image = nil
    URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in

        if error != nil {
            print("error")
            return
        }
        DispatchQueue.main.async(execute: { () -> Void in
            let image = UIImage(data: data!)
            self.image = image
        })

    }).resume()
}}



  }
...