iOS용 Places SDK에서 iOS용 Places Swift SDK로의 마이그레이션은 간단하며 점진적으로 진행할 수 있습니다. iOS용 Places Swift SDK의 구조체는 Objective-C 기반 대응 항목과 호환되지 않으므로 GMSPlacesClient의 API 사용에 따라 개별 기능 청크를 이전하는 것이 좋습니다.
코드를 현대화하고 새 SDK의 기능을 활용하려면 GMSPlacesClient를 PlacesClient로 바꿔야 합니다. 또한 새 메서드에서 매개변수 이름이 변경되므로 매개변수를 with 대신 from로 업데이트해야 합니다. 마지막으로 Places Swift SDK는 업그레이드된 AutocompleteRequest를 사용합니다.
업데이트된 코드
// Initialize Places Swift Client.let_=PlacesClient.provideAPIKey(apiKey)letplacesSwiftClient=PlacesClient.shared
자동 완성 요청 흐름을 업데이트하는 것부터 시작할 수 있습니다. 기존 코드는 콜백을 사용하여 자동 완성 추천을 요청하는 반면 새 코드는 switch/await 패턴을 사용합니다. 콜백은 코드 구조와 오류 처리를 복잡하게 만들 수 있습니다. 새로운 Places Swift SDK는 동시성을 지원하므로 비동기 작업이 간소화됩니다.
// Initialize Places Swift Client.let_=PlacesClient.provideAPIKey(apiKey)letplacesSwiftClient=PlacesClient.shared// Fetch Autocomplete Request.letcenter=CLLocation(latitude:37.3913916,longitude:-122.0879074)letnorthEast=CLLocationCoordinate2DMake(37.388162,-122.088137)letsouthWest=CLLocationCoordinate2DMake(37.395804,-122.077023)letbias=RectangularCoordinateRegion(northEast:northEast,southWest:southWest)letfilter=AutocompleteFilter(types:[.restaurant],origin:center,coordinateRegionBias:bias)letautocompleteRequest=AutocompleteRequest(query:"Sicilian piz",filter:filter)letplaceID:StringswitchawaitplacesSwiftClient.fetchAutocompleteSuggestions(with:autocompleteRequest){case.success(letresults):switchresults.first{case.place(letplaceSuggestion):placeID=placeSuggestion.placeIDcase.none:fallthrough@unknowndefault:return}case.failure(letplacesError):print("Autocomplete error: \(placesError)")return}// Initialize Places Client.GMSPlacesClient.provideAPIKey(apiKey)letplacesClient=GMSPlacesClient.shared()// Fetch Place Request.letmyProperties=[GMSPlaceProperty.name,GMSPlaceProperty.website].map{$0.rawValue}letfetchPlaceRequest=GMSFetchPlaceRequest(placeID:placeID,placeProperties:myProperties,sessionToken:nil)placesClient.fetchPlace(with:fetchPlaceRequest){(place:GMSPlace?,error:Error?)inguardletplace,error==nilelse{return}print("Place found: \(String(describing:place.name)); \(String(describing:place.website))")}
메서드 및 클래스 이름 업데이트
마지막으로 fetchPlace 코드를 리팩터링하고 GMSPlacesClient 초기화와 GMSPlaceProperty 선언을 모두 삭제하여 마이그레이션을 완료합니다. Places Swift SDK에서 메서드 및 클래스 이름이 'GMS' 접두사를 삭제하도록 업데이트되었으며 이에 따라 업데이트해야 합니다.예를 들면 다음과 같습니다. GMSFetchPlaceRequest이 FetchPlaceRequest이 됩니다.
유형 처리
새로운 fetchPlace 메서드는 개선된 유형 처리를 사용합니다. 이전 코드에서는 속성의 원시 값을 전달해야 했지만 새 코드에서는 개발자가 여기에서 원시 값을 명시적으로 가져올 필요가 없어 간결성과 가독성이 향상됩니다.
동시 실행
또한 새 메서드는 동시 실행을 지원하므로 placesSwiftClient.fetchPlace에서 placesClient.fetchPlace의 콜백을 switch/await 패턴으로 대체할 수 있습니다.
// Initialize Places Swift Client.let_=PlacesClient.provideAPIKey(apiKey)letplacesSwiftClient=PlacesClient.shared// Fetch Autocomplete Request.letcenter=CLLocation(latitude:37.3913916,longitude:-122.0879074)letnorthEast=CLLocationCoordinate2DMake(37.388162,-122.088137)letsouthWest=CLLocationCoordinate2DMake(37.395804,-122.077023)letbias=RectangularCoordinateRegion(northEast:northEast,southWest:southWest)letfilter=AutocompleteFilter(types:[.restaurant],origin:center,coordinateRegionBias:bias)letautocompleteRequest=AutocompleteRequest(query:"Sicilian piz",filter:filter)letplaceID:StringswitchawaitplacesSwiftClient.fetchAutocompleteSuggestions(with:autocompleteRequest){case.success(letresults):switchresults.first{case.place(letplaceSuggestion):placeID=placeSuggestion.placeIDcase.none:fallthrough@unknowndefault:return}case.failure(letplacesError):print("Autocomplete error: \(placesError)")return}// Fetch Place Request.letfetchPlaceRequest=FetchPlaceRequest(placeID:placeID,placeProperties:[.displayName,.websiteURL])switchawaitplacesSwiftClient.fetchPlace(with:fetchPlaceRequest){case.success(letplace):print("Place found: \(place.displayName): \(String(describing:place.description))")case.failure(letplacesError):print("Place not found: \(placeID); \(placesError)")}
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[],[],null,["Migrating from Places SDK for iOS to\nPlaces Swift SDK for iOS should be straightforward and can be done\nincrementally. Since structs in the Places Swift SDK for iOS are not\ncompatible with their Objective-C based counterparts, we recommend migrating\ndiscrete chunks of functionality based on uses of APIs in GMSPlacesClient.\n\nAdd the Places Swift SDK for iOS to your project\n\nThe following steps are required to use Places Swift SDK for iOS:\n\n1. Enable the [Places API\n (New)](/maps/documentation/places/ios-sdk/cloud-setup#enabling-apis).\n2. Add the [Places Swift SDK](/maps/documentation/places/ios-sdk/config#googleplacesswift)\n to your dependencies. You can choose to install `GooglePlaces`,\n `GooglePlacesSwift`, or both.\n\n | **Note:** The GitHub URL to access Google Places Swift has changed. If you are updating a version of GooglePlacesSwift that was accessed through the old URL, https://github.com/googlemaps/ios-places-swift-sdk, remove it from your Xcode's package dependencies section.\n3. Initialize the Places client with\n [`PlacesClient`](/maps/documentation/places/ios-sdk/config#googleplacesswift_2).\n\nStep-by-step migration example\n\nAs an example, suppose an app using the Places SDK for iOS\nreceives autocomplete suggestions based on a text input, then fetches the\ndetails of the first place suggestion. Using\nPlaces SDK for iOS, the existing code might look something\nlike the following: \n\n // Initialize Places Client.\n GMSPlacesClient.provideAPIKey(apiKey)\n let client = GMSPlacesClient.shared()\n\n // Fetch Autocomplete Request.\n let center = CLLocation(latitude: 37.3913916, longitude: -122.0879074)\n let northEast = CLLocationCoordinate2DMake(37.388162, -122.088137)\n let southWest = CLLocationCoordinate2DMake(37.395804, -122.077023)\n\n let filter = GMSAutocompleteFilter()\n filter.types = [kGMSPlaceTypeRestaurant]\n filter.origin = center\n filter.locationBias = GMSPlaceRectangularLocationOption(northEast, southWest)\n\n let request = GMSAutocompleteRequest(query: \"Sicilian piz\")\n request.filter = filter\n\n client.fetchAutocompleteSuggestions(from: request) { (results, error) in\n guard let results, error == nil else {\n print(\"Autocomplete error: \\\\(String(describing: error))\")\n return\n }\n // Fetch Place Request.\n guard let placeID = results.first?.placeSuggestion?.placeID else { return }\n let myProperties = \\[GMSPlaceProperty.name, GMSPlaceProperty.website\\].map {$0.rawValue}\n let fetchPlaceRequest = GMSFetchPlaceRequest(placeID: placeID, placeProperties: myProperties, sessionToken: nil)\n client.fetchPlace(with: fetchPlaceRequest) { (place: GMSPlace?, error: Error?) in\n guard let place, error == nil else { return }\n print(\"Place found: \\\\(String(describing: place.name)); \\\\(String(describing: place.website))\")\n }\n }\n\nUpdate the Places Client initializer\n\nTo modernize the code and take advantage of the new SDK's capabilities, you'll\nneed to replace the GMSPlacesClient with the PlacesClient. Additionally, the\nparameter names are changed in the new method, so you'll need to update the\nparameter to `from` instead of `with`. Finally, the\nPlaces Swift SDK uses the upgraded\n[AutocompleteRequest](/maps/documentation/places/ios-sdk/reference/swift/Structs/AutocompleteRequest). \n\nUpdated code \n\n // Initialize Places Swift Client.\n let _ = PlacesClient.provideAPIKey(apiKey)\n let placesSwiftClient = PlacesClient.shared\n\nOriginal code \n\n // Initialize Places Client.\n GMSPlacesClient.provideAPIKey(apiKey)\n let client = GMSPlacesClient.shared()\n\nUpdate the autocomplete request\n\nYou could begin by updating the autocomplete request flow. The old code uses a\ncallback to request autocomplete suggestions, while the new code employs a\n`switch`/`await` pattern. Callbacks can add complexity to code structure and\nerror handling. The new Places Swift SDK supports concurrency,\nwhich simplifies asynchronous operations. \n\n // Initialize Places Swift Client.\n let _ = PlacesClient.provideAPIKey(apiKey)\n let placesSwiftClient = PlacesClient.shared\n\n // Fetch Autocomplete Request.\n let center = CLLocation(latitude: 37.3913916, longitude: -122.0879074)\n let northEast = CLLocationCoordinate2DMake(37.388162, -122.088137)\n let southWest = CLLocationCoordinate2DMake(37.395804, -122.077023)\n\n let bias = RectangularCoordinateRegion(northEast: northEast, southWest: southWest)\n let filter = AutocompleteFilter(types: [ .restaurant ], origin: center, coordinateRegionBias: bias)\n\n let autocompleteRequest = AutocompleteRequest(query: \"Sicilian piz\", filter: filter)\n let placeID: String\n switch await placesSwiftClient.fetchAutocompleteSuggestions(with: autocompleteRequest) {\n case .success(let results):\n switch results.first {\n case .place(let placeSuggestion):\n placeID = placeSuggestion.placeID\n case .none:\n fallthrough\n @unknown default:\n return\n }\n case .failure(let placesError):\n print(\"Autocomplete error: \\\\(placesError)\")\n return\n }\n\n // Initialize Places Client.\n GMSPlacesClient.provideAPIKey(apiKey)\n let placesClient = GMSPlacesClient.shared()\n\n // Fetch Place Request.\n let myProperties = [GMSPlaceProperty.name, GMSPlaceProperty.website].map {$0.rawValue}\n\n let fetchPlaceRequest = GMSFetchPlaceRequest(placeID: placeID, placeProperties: myProperties, sessionToken: nil)\n\n placesClient.fetchPlace(with: fetchPlaceRequest) { (place: GMSPlace?, error: Error?) in\n guard let place, error == nil else { return }\n print(\"Place found: \\(String(describing: place.name)); \\(String(describing: place.website))\")\n }\n\nUpdate method and class names\n\nFinally, complete the migration by refactoring the `fetchPlace` code and\nremoving both the `GMSPlacesClient` initialization and `GMSPlaceProperty`\ndeclaration. In Places Swift SDK, the method and classnames\nhave been updated to remove the \"GMS\" prefix, and must be updated accordingly;\ne.g., `GMSFetchPlaceRequest` becomes `FetchPlaceRequest`.\n\nType-handling\n\nThe new `fetchPlace` method uses improved type handling. While the old code\nrequired passing the property's raw values, the new code doesn't require\ndevelopers to explicitly fetch raw values here, thereby improving concision and\nreadability.\n\nConcurrency\n\nAdditionally, the new method supports concurrency, allowing for replacing the\ncallback in `placesClient.fetchPlace` with a `switch`/`await` pattern in\n`placesSwiftClient.fetchPlace`. \n\n // Initialize Places Swift Client.\n let _ = PlacesClient.provideAPIKey(apiKey)\n let placesSwiftClient = PlacesClient.shared\n\n // Fetch Autocomplete Request.\n let center = CLLocation(latitude: 37.3913916, longitude: -122.0879074)\n let northEast = CLLocationCoordinate2DMake(37.388162, -122.088137)\n let southWest = CLLocationCoordinate2DMake(37.395804, -122.077023)\n\n let bias = RectangularCoordinateRegion(northEast: northEast, southWest: southWest)\n let filter = AutocompleteFilter(types: [ .restaurant ], origin: center, coordinateRegionBias: bias)\n\n let autocompleteRequest = AutocompleteRequest(query: \"Sicilian piz\", filter: filter)\n let placeID: String\n switch await placesSwiftClient.fetchAutocompleteSuggestions(with: autocompleteRequest) {\n case .success(let results):\n switch results.first {\n case .place(let placeSuggestion):\n placeID = placeSuggestion.placeID\n case .none:\n fallthrough\n @unknown default:\n return\n }\n case .failure(let placesError):\n print(\"Autocomplete error: \\(placesError)\")\n return\n }\n\n // Fetch Place Request.\n let fetchPlaceRequest = FetchPlaceRequest(placeID: placeID, placeProperties: \\[.displayName, .websiteURL\\])\n switch await placesSwiftClient.fetchPlace(with: fetchPlaceRequest) {\n case .success(let place):\n print(\"Place found: \\\\(place.displayName): \\\\(String(describing: place.description))\")\n case .failure(let placesError):\n print(\"Place not found: \\\\(placeID); \\\\(placesError)\")\n }\n\nStay up-to-date\n\nVisit the [release notes page for Places Swift SDK for iOS](/maps/documentation/places/ios-sdk/places-swift-release-notes) to learn\nabout new features and changes."]]