# How to import recipes from TikTok and Instagram links in an iOS app

To import a recipe from a TikTok or Instagram post into an iOS app, pass the
post's link to the ClipParse iOS SDK. It returns the recipe as structured
data: the title, ingredients with quantities and units, ordered steps,
timings and servings.

You need a ClipParse API key: get a free one at
[clipparse.com/get-free-key](https://clipparse.com/get-free-key). It takes
seconds and doesn't require a credit card.

For a complete app built from this guide's code, see
[tiktok-instagram-recipe-import-swiftui](https://github.com/clipparse/tiktok-instagram-recipe-import-swiftui)
on GitHub: a SwiftUI app with a share extension.

## Requirements

- iOS 15 or later, or macOS 12 or later
- Swift 5.9 or later, Xcode 15 or later
- A ClipParse API key

## Add the SDK

In Xcode, choose **File → Add Package Dependencies…** and enter:

```text
https://github.com/clipparse/clipparse-ios-sdk
```

Or add it to your `Package.swift`:

```swift
dependencies: [
    .package(url: "https://github.com/clipparse/clipparse-ios-sdk", from: "1.5.0")
]
```

## Extract a recipe from a link

Create a client with your API key, then call `extract` with the post's URL.
It returns one of two outcomes: `.recipe` with the recipe, or `.noRecipe`
when the post holds no usable recipe. A post with no recipe is an expected
outcome, not an error.

```swift
import ClipParse

let client = ClipParseClient(apiKey: "<your API key>")

let url = URL(string: "https://www.tiktok.com/@somecreator/video/1234567890")!
switch try await client.extract(url) {
case .recipe(let recipe):
    print(recipe.title)
    for ingredient in recipe.ingredients {
        print(ingredient.raw)
    }
    for step in recipe.steps {
        print(step.text)
    }
case .noRecipe(let reason):
    print("No recipe found:", reason)
@unknown default:
    print("We couldn't import a recipe from this post.")
}
```

`.noRecipe` carries a reason: `.noRecipeFound` when the post holds no recipe,
or `.multipleRecipesDetected` when it holds several recipes in one post.

Keep the `@unknown default` branch: later versions of the SDK can add
outcomes.

## Wire it into a SwiftUI screen

A small view model that imports a link and keeps either the recipe or a
message to show the user:

```swift
import ClipParse
import SwiftUI

@MainActor
final class RecipeImportModel: ObservableObject {
    @Published var recipe: ClipParse.Recipe?
    @Published var message: String?

    private let client = ClipParseClient(apiKey: "<your API key>")

    func importRecipe(from link: String) async {
        recipe = nil
        message = nil
        guard let url = URL(string: link.trimmingCharacters(in: .whitespacesAndNewlines)) else {
            message = "That doesn't look like a link."
            return
        }
        do {
            switch try await client.extract(url) {
            case .recipe(let found):
                recipe = found
            case .noRecipe(.multipleRecipesDetected):
                message = "This post has more than one recipe."
            case .noRecipe:
                message = "We couldn't find a recipe in this post."
            @unknown default:
                message = "We couldn't import a recipe from this post."
            }
        } catch {
            message = importErrorMessage(for: error)
        }
    }
}
```

## Handle errors

Failures throw a typed `ClipParseError`. Turn them into messages for the user:

```swift
func importErrorMessage(for error: Error) -> String {
    switch error {
    case ClipParseError.unsupportedPlatform:
        return "Only TikTok and Instagram links are supported."
    case ClipParseError.postUnavailable:
        return "This post was deleted, is private, or doesn't exist."
    case ClipParseError.unauthorized, ClipParseError.invalidAPIKey, ClipParseError.apiKeyRevoked:
        print("ClipParse API key error:", error)
        return "Recipe import isn't available right now."
    case ClipParseError.quotaExceeded, ClipParseError.rateLimited:
        return "Too many imports right now. Try again later."
    case ClipParseError.network:
        return "Check your connection and try again."
    default:
        return "Something went wrong. Please try again."
    }
}
```

The API key errors (`unauthorized`, `invalidAPIKey`, `apiKeyRevoked`) are
yours to fix, not the user's: log them so you notice. `rateLimited` and
`quotaExceeded` carry a `retryAfter` interval in seconds; `quotaExceeded`
gives `nil` when the allowance doesn't renew. Errors where `isRetryable` is
true, such as a dropped connection, are safe to retry.

## Use the recipe's fields

The recipe's fields:

- `title`, and `language`: a short code such as `"en"`.
- `sourceUrl`: the post the recipe came from.
- `thumbnailUrl`: the post's thumbnail, when there is one. The URL expires,
  so download the image if you keep the recipe.
- `servings`, `prepTimeMinutes` and `cookTimeMinutes`, when the post states
  them.
- `ingredients`, in the order the post lists them. Each has a `name`, a
  `quantity` and a `unit`, the `prep` note (such as "finely chopped"), the
  `section` it belongs to (such as "For the sauce"), and `raw`: the line
  exactly as the post wrote it.
- `steps`, in order. Each has its `text`, a `durationMinutes` when stated,
  and a `section`.

Anything the post doesn't state is `nil`. For a range such as "2-3 tbsp",
`quantity` is the midpoint and `quantityMin` and `quantityMax` hold the ends.
`unit` is `.each` for counted ingredients such as 3 eggs.

To show an amount, use the range when there is one:

```swift
func amountText(_ ingredient: ClipParse.Ingredient) -> String? {
    guard let quantity = ingredient.quantity else { return nil }
    var amount = quantity.formatted()
    if let low = ingredient.quantityMin, let high = ingredient.quantityMax {
        amount = "\(low.formatted())–\(high.formatted())"
    }
    switch ingredient.unit {
    case nil, .each:
        return amount
    case let unit?:
        return "\(amount) \(unit.rawValue)"
    }
}
```

## Accept links from the share sheet

People find recipes in the TikTok and Instagram apps, so the smoothest way in
is the share sheet: the user taps Share on a post and picks your app. Add a
Share Extension target, set `NSExtensionActivationSupportsWebURLWithMaxCount`
to `1` in its `NSExtensionActivationRule`, and read the shared URL:

```swift
import UniformTypeIdentifiers

let provider = (extensionContext?.inputItems.first as? NSExtensionItem)?
    .attachments?
    .first { $0.hasItemConformingToTypeIdentifier(UTType.url.identifier) }
provider?.loadItem(forTypeIdentifier: UTType.url.identifier) { item, _ in
    guard let url = item as? URL else { return }
    handleSharedLink(url)
}
```

`handleSharedLink` is yours: pass the URL to the same import code, in the
extension or in your app.

## Next steps

- The [example app](https://github.com/clipparse/tiktok-instagram-recipe-import-swiftui)
  is this guide's code as a complete app, ready to run.
- The [API reference](https://docs.clipparse.com/) lists every field and
  outcome.
- The [ClipParse iOS SDK](https://github.com/clipparse/clipparse-ios-sdk)
  repository has the changelog.
- [Pricing](https://clipparse.com/pricing) covers what each import costs and
  the plans past the free tier.
