Chuyển sang SDK Swift của Địa điểm dành cho iOS

Việc di chuyển từ Places SDK for iOS sang Places Swift SDK for iOS sẽ diễn ra một cách đơn giản và có thể thực hiện từng bước. Vì các cấu trúc trong Places Swift SDK cho iOS không tương thích với các cấu trúc tương ứng dựa trên Objective-C, nên bạn nên di chuyển các khối chức năng rời rạc dựa trên việc sử dụng API trong GMSPlacesClient.

Thêm Places Swift SDK cho iOS vào dự án của bạn

Bạn phải thực hiện các bước sau để sử dụng Places Swift SDK cho iOS:

  1. Bật Places API (mới).
  2. Thêm Places Swift SDK vào các phần phụ thuộc của bạn. Bạn có thể chọn cài đặt GooglePlaces, GooglePlacesSwift hoặc cả hai.

  3. Khởi động ứng dụng Places bằng PlacesClient.

Ví dụ về quy trình di chuyển từng bước

Ví dụ: giả sử một ứng dụng sử dụng Places SDK cho iOS nhận được các đề xuất tự động hoàn thành dựa trên một văn bản đầu vào, sau đó tìm nạp thông tin chi tiết về đề xuất địa điểm đầu tiên. Khi sử dụng Places SDK for iOS, mã hiện có có thể trông như sau:

// Initialize Places Client.
GMSPlacesClient.provideAPIKey(apiKey)
let client = GMSPlacesClient.shared()

// Fetch Autocomplete Request.
let center = CLLocation(latitude: 37.3913916, longitude: -122.0879074)
let northEast = CLLocationCoordinate2DMake(37.388162, -122.088137)
let southWest = CLLocationCoordinate2DMake(37.395804, -122.077023)

let filter = GMSAutocompleteFilter()
filter.types = [kGMSPlaceTypeRestaurant]
filter.origin = center
filter.locationBias = GMSPlaceRectangularLocationOption(northEast, southWest)

let request = GMSAutocompleteRequest(query: "Sicilian piz")
request.filter = filter

client.fetchAutocompleteSuggestions(from: request) { (results, error) in
  guard let results, error == nil else {
    print("Autocomplete error: \(String(describing: error))")
    return
  }

  // Fetch Place Request.
  guard let placeID = results.first?.placeSuggestion?.placeID else { return }
  let myProperties = [GMSPlaceProperty.name, GMSPlaceProperty.website].map {$0.rawValue}

  let fetchPlaceRequest = GMSFetchPlaceRequest(placeID: placeID, placeProperties: myProperties, sessionToken: nil)

  client.fetchPlace(with: fetchPlaceRequest) { (place: GMSPlace?, error: Error?) in
    guard let place, error == nil else { return }
    print("Place found: \(String(describing: place.name)); \(String(describing: place.website))")
  }
}

Cập nhật trình khởi tạo Places Client

Để hiện đại hoá mã và tận dụng các chức năng của SDK mới, bạn cần thay thế GMSPlacesClient bằng PlacesClient. Ngoài ra, tên tham số sẽ thay đổi trong phương thức mới, vì vậy, bạn cần cập nhật tham số thành from thay vì with. Cuối cùng, Places Swift SDK sẽ sử dụng AutocompleteRequest đã nâng cấp.

Đã cập nhật mã

// Initialize Places Swift Client.
let _ = PlacesClient.provideAPIKey(apiKey)
let placesSwiftClient = PlacesClient.shared

Mã gốc

// Initialize Places Client.
GMSPlacesClient.provideAPIKey(apiKey)
let client = GMSPlacesClient.shared()

Cập nhật yêu cầu tự động hoàn thành

Bạn có thể bắt đầu bằng cách cập nhật quy trình yêu cầu tự động hoàn tất. Mã cũ sử dụng một lệnh gọi lại để yêu cầu các đề xuất tự động hoàn thành, trong khi mã mới sử dụng mẫu switch/await. Lệnh gọi lại có thể làm tăng độ phức tạp cho cấu trúc mã và việc xử lý lỗi. Places Swift SDK mới hỗ trợ tính đồng thời, giúp đơn giản hoá các thao tác không đồng bộ.

// Initialize Places Swift Client.
let _ = PlacesClient.provideAPIKey(apiKey)
let placesSwiftClient = PlacesClient.shared

// Fetch Autocomplete Request.
let center = CLLocation(latitude: 37.3913916, longitude: -122.0879074)
let northEast = CLLocationCoordinate2DMake(37.388162, -122.088137)
let southWest = CLLocationCoordinate2DMake(37.395804, -122.077023)

let bias = RectangularCoordinateRegion(northEast: northEast, southWest: southWest)
let filter = AutocompleteFilter(types: [ .restaurant ], origin: center, coordinateRegionBias: bias)

let autocompleteRequest = AutocompleteRequest(query: "Sicilian piz", filter: filter)
let placeID: String
switch await placesSwiftClient.fetchAutocompleteSuggestions(with: autocompleteRequest) {
case .success(let results):
  switch results.first {
  case .place(let placeSuggestion):
    placeID = placeSuggestion.placeID
  case .none:
    fallthrough
  @unknown default:
    return
  }
case .failure(let placesError):
  print("Autocomplete error: \(placesError)")
  return
}

// Initialize Places Client.
GMSPlacesClient.provideAPIKey(apiKey)
let placesClient = GMSPlacesClient.shared()

// Fetch Place Request.
let myProperties = [GMSPlaceProperty.name, GMSPlaceProperty.website].map {$0.rawValue}

let fetchPlaceRequest = GMSFetchPlaceRequest(placeID: placeID, placeProperties: myProperties, sessionToken: nil)

placesClient.fetchPlace(with: fetchPlaceRequest) { (place: GMSPlace?, error: Error?) in
  guard let place, error == nil else { return }
  print("Place found: \(String(describing: place.name)); \(String(describing: place.website))")
}

Cập nhật tên phương thức và tên lớp

Cuối cùng, hãy hoàn tất quá trình di chuyển bằng cách tái cấu trúc mã fetchPlace và xoá cả quá trình khởi chạy GMSPlacesClient và khai báo GMSPlaceProperty. Trong Places Swift SDK, phương thức và tên lớp đã được cập nhật để xoá tiền tố "GMS" và bạn phải cập nhật cho phù hợp; ví dụ: GMSFetchPlaceRequest trở thành FetchPlaceRequest.

Xử lý kiểu

Phương thức fetchPlace mới sử dụng tính năng xử lý loại được cải thiện. Mặc dù mã cũ yêu cầu truyền các giá trị thô của thuộc tính, nhưng mã mới không yêu cầu nhà phát triển phải tìm nạp rõ ràng các giá trị thô tại đây, nhờ đó cải thiện tính súc tích và khả năng đọc.

Đồng thời

Ngoài ra, phương thức mới này hỗ trợ tính đồng thời, cho phép thay thế lệnh gọi lại trong placesClient.fetchPlace bằng mẫu switch/await trong placesSwiftClient.fetchPlace.

// Initialize Places Swift Client.
let _ = PlacesClient.provideAPIKey(apiKey)
let placesSwiftClient = PlacesClient.shared

// Fetch Autocomplete Request.
let center = CLLocation(latitude: 37.3913916, longitude: -122.0879074)
let northEast = CLLocationCoordinate2DMake(37.388162, -122.088137)
let southWest = CLLocationCoordinate2DMake(37.395804, -122.077023)

let bias = RectangularCoordinateRegion(northEast: northEast, southWest: southWest)
let filter = AutocompleteFilter(types: [ .restaurant ], origin: center, coordinateRegionBias: bias)

let autocompleteRequest = AutocompleteRequest(query: "Sicilian piz", filter: filter)
let placeID: String
switch await placesSwiftClient.fetchAutocompleteSuggestions(with: autocompleteRequest) {
case .success(let results):
  switch results.first {
  case .place(let placeSuggestion):
    placeID = placeSuggestion.placeID
  case .none:
    fallthrough
  @unknown default:
    return
  }
case .failure(let placesError):
  print("Autocomplete error: \(placesError)")
  return
}

// Fetch Place Request.
let fetchPlaceRequest = FetchPlaceRequest(placeID: placeID, placeProperties: [.displayName, .websiteURL])
switch await placesSwiftClient.fetchPlace(with: fetchPlaceRequest) {
case .success(let place):
  print("Place found: \(place.displayName): \(String(describing: place.description))")

case .failure(let placesError):
  print("Place not found: \(placeID); \(placesError)")
}

Luôn nắm bắt tình hình

Truy cập vào trang ghi chú phát hành của Places Swift SDK cho iOS để tìm hiểu về các tính năng và thay đổi mới.