// Note: You can specify any of the 15 languages entity extraction supports here. letoptions=EntityExtractorOptions(modelIdentifier:EntityExtractionModelIdentifier.english)letentityExtractor=EntityExtractor.entityExtractor(options:options)
Objective-C
// Note: You can specify any of the 15 languages entity extraction supports here. MLKEntityExtractorOptions*options=[[MLKEntityExtractorOptionsalloc]initWithModelIdentifier:MLKEntityExtractionModelIdentifierEnglish];MLKEntityExtractor*entityExtractor=[MLKEntityExtractorentityExtractorWithOptions:options];
接著,請確認已將必要的語言模型下載到裝置:
Swift
entityExtractor.downloadModelIfNeeded(completion:{// If the error is nil, the download completed successfully.})
Objective-C
[entityExtractordownloadModelIfNeededWithCompletion:^(NSError*_Nullableerror){// If the error is nil, the download completed successfully.}];
// The EntityExtractionParams parameter is optional. Only instantiate and// configure one if you need to customize one or more of its params.varparams=EntityExtractionParams()// The params object contains the following properties which can be customized on// each annotateText: call. Please see the class's documentation for a more// detailed description of what each property represents.params.referenceTime=Date();params.referenceTimeZone=TimeZone(identifier:"GMT");params.preferredLocale=Locale(identifier:"en-US");params.typesFilter=Set([EntityType.address,EntityType.dateTime])extractor.annotateText(text.string,params:params,completion:{result,errorin// If the error is nil, the annotation completed successfully and any results // will be contained in the `result` array.})
Objective-C
// The MLKEntityExtractionParams property is optional. Only instantiate and// configure one if you need to customize one or more of its params.MLKEntityExtractionParams*params=[[MLKEntityExtractionParamsalloc]init];// The params object contains the following properties which can be customized on// each annotateText: call. Please see the class's documentation for a fuller // description of what each property represents.params.referenceTime=[NSDatedate];params.referenceTimeZone=[NSTimeZonetimeZoneWithAbbreviation:@"GMT"];params.preferredLocale=[NSLocalelocalWithLocaleIdentifier:@"en-US"];params.typesFilter=[NSSetsetWithObjects:MLKEntityExtractionEntityTypeAddress,MLKEntityExtractionEntityTypeDateTime,nil];[extractorannotateText:text.stringwithParams:paramscompletion:^(NSArray*_Nullableresult,NSError*_Nullableerror){// If the error is nil, the annotation completed successfully and any results // will be contained in the `result` array.}
迴圈註解結果,擷取已辨識實體的相關資訊。
Swift
// let annotations be the Array! returned from EntityExtractorforannotationinannotations{letentities=annotation.entitiesforentityinentities{switchentity.entityType{caseEntityType.dateTime:guardletdateTimeEntity=entity.dateTimeEntityelse{print("This field should be populated.")return}print("Granularity: %d",dateTimeEntity.dateTimeGranularity)print("DateTime: %@",dateTimeEntity.dateTime)caseEntityType.flightNumber:guardletflightNumberEntity=entity.flightNumberEntityelse{print("This field should be populated.")return}print("Airline Code: %@",flightNumberEntity.airlineCode)print("Flight number: %@",flightNumberEntity.flightNumber)caseEntityType.money:guardletmoneyEntity=entity.moneyEntityelse{print("This field should be populated.")return}print("Currency: %@",moneyEntity.integerPart)print("Integer Part: %d",moneyEntity.integerPart)print("Fractional Part: %d",moneyEntity.fractionalPart)// Add additional cases as needed.default:print("Entity: %@",entity);}}}
Objective-C
NSArray*annotations;// Returned from EntityExtractorfor(MLKEntityAnnotation*annotationinannotations){NSArray*entities=annotation.entities;NSLog(@"Range: [%d, %d)",(int)annotation.range.location,(int)(annotation.range.location+annotation.range.length));for(MLKEntity*entityinentities){if([entity.entityTypeisEqualToString:MLKEntityExtractionEntityTypeDateTime]){MLKDateTimeEntity*dateTimeEntity=entity.dateTimeEntity;NSLog(@"Granularity: %d",(int)dateTimeEntity.dateTimeGranularity);NSLog(@"DateTime: %@",dateTimeEntity.dateTime);break;}elseif([entity.entityTypeisEqualToString:MLKEntityExtractionEntityTypeFlightNumber]){MLKFlightNumberEntity*flightNumberEntity=entity.flightNumberEntity;NSLog(@"Airline Code: %@",flightNumberEntity.airlineCode);NSLog(@"Flight number: %@",flightNumberEntity.flightNumber);break;}elseif([entity.entityTypeisEqualToString:MLKEntityExtractionEntityTypeMoney]){MLKMoneyEntity*moneyEntity=entity.moneyEntity;NSLog(@"Currency: %@",moneyEntity.unnormalizedCurrency);NSLog(@"Integer Part: %d",(int)moneyEntity.integerPart);NSLog(@"Fractional Part: %d",(int)moneyEntity.fractionalPart);break;}else{// Add additional cases as needed.NSLog(@"Entity: %@",entity);}}
[null,null,["上次更新時間:2025-08-29 (世界標準時間)。"],[[["\u003cp\u003eThis is a beta API for extracting entities (like dates, addresses, flight numbers) from text using machine learning.\u003c/p\u003e\n"],["\u003cp\u003eThe API requires adding the \u003ccode\u003eGoogleMLKit/EntityExtraction\u003c/code\u003e pod and downloading language models before use.\u003c/p\u003e\n"],["\u003cp\u003eYou can customize the entity extraction process by specifying language, time zone, and filtering for specific entity types.\u003c/p\u003e\n"],["\u003cp\u003eThe API returns an array of \u003ccode\u003eEntityAnnotation\u003c/code\u003e objects containing information about each identified entity in the text.\u003c/p\u003e\n"],["\u003cp\u003eThis API has a 10.7MB footprint and is only compatible with 64-bit devices running iOS.\u003c/p\u003e\n"]]],["The ML Kit entity extraction API analyzes text to identify entities. To use it, include the `GoogleMLKit/EntityExtraction` library, create `EntityExtractorOptions`, and instantiate an `EntityExtractor`. Download the required language model and then use the `annotateText` method, optionally with `EntityExtractionParams` for customization. The API returns a list of `EntityAnnotation` objects. The API is in beta and adds 10.7MB to your app.\n"],null,["| This API is offered in beta, and is not subject to any SLA or deprecation policy. Changes may be made to this API that break backward compatibility.\n\nTo analyze a piece of text and extract the\nentities in it, invoke the ML Kit entity extraction API by passing\nthe text directly to its `annotateText:completion:` method. It is also possible to\npass in an optional `EntityExtractionParams` object which contains other\nconfiguration options such as a reference time, timezone, or\na filter to limit the search for a subset of entity types.\nThe API returns a list of `EntityAnnotation` objects containing information about each entity.\n\nThe entity extraction base detector assets are statically linked at app run time.\nThey add about 10.7MB to your app.\n| **Note:** ML Kit iOS APIs only run on 64-bit devices. If you build your app with 32-bit support, check the device's architecture before using this API.\n\nTry it out\n\n- Play around with [the sample app](https://github.com/googlesamples/mlkit/tree/master/ios/quickstarts/entityextraction) to see an example usage of this API.\n\nBefore you begin\n\n1. Include the following ML Kit libraries in your Podfile:\n\n pod 'GoogleMLKit/EntityExtraction', '8.0.0'\n\n2. After you install or update your project's Pods, open your Xcode project using its .xcworkspace. ML Kit is supported in Xcode version 13.2.1 or higher.\n\nExtract entities from text\n\nTo extract entities from text, first create an `EntityExtractorOptions` object by specifying the language and use that to instantiate an `EntityExtractor`: \n\nSwift \n\n```swift\n// Note: You can specify any of the 15 languages entity extraction supports here. \nlet options = EntityExtractorOptions(modelIdentifier: \n EntityExtractionModelIdentifier.english)\nlet entityExtractor = EntityExtractor.entityExtractor(options: options)\n```\n\nObjective-C \n\n```objective-c\n// Note: You can specify any of the 15 languages entity extraction supports here. \nMLKEntityExtractorOptions *options = \n [[MLKEntityExtractorOptions alloc] \n initWithModelIdentifier:MLKEntityExtractionModelIdentifierEnglish];\n\nMLKEntityExtractor *entityExtractor = \n [MLKEntityExtractor entityExtractorWithOptions:options];\n```\n\nNext, ensure that the required language model is downloaded to the device: \n\nSwift \n\n```swift\nentityExtractor.downloadModelIfNeeded(completion: {\n // If the error is nil, the download completed successfully.\n})\n```\n\nObjective-C \n\n```objective-c\n[entityExtractor downloadModelIfNeededWithCompletion:^(NSError *_Nullable error) {\n // If the error is nil, the download completed successfully.\n}];\n```\n\nOnce the model has been downloaded, pass a string and an optional\n`MLKEntityExtractionParams` to the `annotate` method. \n\nSwift \n\n```swift\n// The EntityExtractionParams parameter is optional. Only instantiate and\n// configure one if you need to customize one or more of its params.\nvar params = EntityExtractionParams()\n// The params object contains the following properties which can be customized on\n// each annotateText: call. Please see the class's documentation for a more\n// detailed description of what each property represents.\nparams.referenceTime = Date();\nparams.referenceTimeZone = TimeZone(identifier: \"GMT\");\nparams.preferredLocale = Locale(identifier: \"en-US\");\nparams.typesFilter = Set([EntityType.address, EntityType.dateTime])\n\nextractor.annotateText(\n text.string,\n params: params,\n completion: {\n result, error in\n // If the error is nil, the annotation completed successfully and any results \n // will be contained in the `result` array.\n }\n)\n```\n\nObjective-C \n\n```objective-c\n// The MLKEntityExtractionParams property is optional. Only instantiate and\n// configure one if you need to customize one or more of its params.\nMLKEntityExtractionParams *params = [[MLKEntityExtractionParams alloc] init];\n// The params object contains the following properties which can be customized on\n// each annotateText: call. Please see the class's documentation for a fuller \n// description of what each property represents.\nparams.referenceTime = [NSDate date];\nparams.referenceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@\"GMT\"];\nparams.preferredLocale = [NSLocale localWithLocaleIdentifier:@\"en-US\"];\nparams.typesFilter = \n [NSSet setWithObjects:MLKEntityExtractionEntityTypeAddress, \n MLKEntityExtractionEntityTypeDateTime, nil];\n\n[extractor annotateText:text.string\n withParams:params\n completion:^(NSArray *_Nullable result, NSError *_Nullable error) {\n // If the error is nil, the annotation completed successfully and any results \n // will be contained in the `result` array.\n}\n```\n\nLoop over the annotation results to retrieve information about the\nrecognized entities. \n\nSwift \n\n```swift\n// let annotations be the Array! returned from EntityExtractor\nfor annotation in annotations {\n let entities = annotation.entities\n for entity in entities {\n switch entity.entityType {\n case EntityType.dateTime:\n guard let dateTimeEntity = entity.dateTimeEntity else {\n print(\"This field should be populated.\")\n return\n }\n print(\"Granularity: %d\", dateTimeEntity.dateTimeGranularity)\n print(\"DateTime: %@\", dateTimeEntity.dateTime)\n case EntityType.flightNumber:\n guard let flightNumberEntity = entity.flightNumberEntity else {\n print(\"This field should be populated.\")\n return\n }\n print(\"Airline Code: %@\", flightNumberEntity.airlineCode)\n print(\"Flight number: %@\", flightNumberEntity.flightNumber)\n case EntityType.money:\n guard let moneyEntity = entity.moneyEntity else {\n print(\"This field should be populated.\")\n return\n }\n print(\"Currency: %@\", moneyEntity.integerPart)\n print(\"Integer Part: %d\", moneyEntity.integerPart)\n print(\"Fractional Part: %d\", moneyEntity.fractionalPart)\n // Add additional cases as needed.\n default:\n print(\"Entity: %@\", entity);\n }\n }\n}\n```\n\nObjective-C \n\n```objective-c\nNSArray *annotations; // Returned from EntityExtractor\n\nfor (MLKEntityAnnotation *annotation in annotations) {\n NSArray *entities = annotation.entities;\n NSLog(@\"Range: [%d, %d)\", (int)annotation.range.location, (int)(annotation.range.location + annotation.range.length));\n for (MLKEntity *entity in entities) {\n if ([entity.entityType isEqualToString:MLKEntityExtractionEntityTypeDateTime]) {\n MLKDateTimeEntity *dateTimeEntity = entity.dateTimeEntity;\n NSLog(@\"Granularity: %d\", (int)dateTimeEntity.dateTimeGranularity);\n NSLog(@\"DateTime: %@\", dateTimeEntity.dateTime);\n break;\n } else if ([entity.entityType isEqualToString:MLKEntityExtractionEntityTypeFlightNumber]) {\n MLKFlightNumberEntity *flightNumberEntity = entity.flightNumberEntity;\n NSLog(@\"Airline Code: %@\", flightNumberEntity.airlineCode);\n NSLog(@\"Flight number: %@\", flightNumberEntity.flightNumber);\n break;\n } else if ([entity.entityType isEqualToString:MLKEntityExtractionEntityTypeMoney]) {\n MLKMoneyEntity *moneyEntity = entity.moneyEntity;\n NSLog(@\"Currency: %@\", moneyEntity.unnormalizedCurrency);\n NSLog(@\"Integer Part: %d\", (int)moneyEntity.integerPart);\n NSLog(@\"Fractional Part: %d\", (int)moneyEntity.fractionalPart);\n break;\n } else {\n // Add additional cases as needed.\n NSLog(@\"Entity: %@\", entity);\n }\n }\n```"]]