Giter VIP home page Giter VIP logo

swift-sanity's Introduction

Swift Sanity

Code for interacting with Sanity content from Swift on iOS and macOS. This package is under development and may long term aim for feature parity with the JavaScript client, but for the time being is limited to groq queries, realtime listening and image asset url generation.

Queries

You can perform queries with typed results, or untyped.

Typed results

Simply pass in a type to the query function.

import Foundation
import Sanity

let client = SanityClient(projectId: "3do82whm", dataset: "next")

// Our result type
struct Post: Decodable {
    let title: String
    let slug: String?
    let poster: SanityType.Image
}

var groq = """
* [_type == "post"] {
  title,
  "slug": slug.current,
  poster
}[0...1]
"""

let query = client.query([Post].self, query: groq)

query.fetch { completion in
    /// Receive and update values on the main queue
    DispatchQueue.main.async {
        switch(completion) {
        case .success(let response):
            dump(response.result)
        case .failure(let error):
            dump(error)
        }
    }
}

outputs

1 element
  ▿ QueryTester.Post
    - title: "Introducing Glush: a robust, human readable, top-down parser compiler"
    ▿ slug: Optional("why-we-wrote-yet-another-parser-compiler")
      - some: "why-we-wrote-yet-another-parser-compiler"
    ▿ poster: Sanity.SanityType.Image
      - id: "18b2c50584718e1356e696ab22a3499e4ba65b55"
      - width: 5760
      - height: 3840
      - format: "png"
      ▿ asset: Sanity.SanityType.Ref
        - _ref: "image-18b2c50584718e1356e696ab22a3499e4ba65b55-5760x3840-png"
        - _type: "reference"
      - crop: nil
      - hotspot: nil
      - validImage: true

Untyped results

Omitting the type will return a success type with Data. All status codes less than 300 will return a success value. See https://www.sanity.io/docs/http-query for information about the response object

// ...
let query = client.query(query: groq)

query.fetch { completion in
    switch(completion) {
    case .success(let data):
        let jsonString = String(data: data, encoding: .utf8)
        print(data)
    case .failure(let error):
        dump(error)
    }
}

Query Listening

See the example app for an example of listening to queries. This will push new results to you as content changes server side.

Sanity.io documentation on realtime updates

Generate image asset URLs

This module provides SanityType.Image which when put through imageURL on SanityClient will generate image asset URLs which respect any hotspot or crop rect set by editors.

let client = SanityClient(projectId: "zp7mbokg", dataset: "production")
let image = SanityType.Image(
    asset: SanityType.Ref(
        _ref: "image-Tb9Ew8CXIwaY6R1kjMvI0uRR-2000x3000-jpg",
        _type: "reference"
    ),
    crop: SanityType.Image.Crop(
        bottom: 0.1,
        left: 0.1,
        top: 0.1,
        right: 0.1
    ),
    hotspot: SanityType.Image.Hotspot(
        width: 0.3,
        height: 0.3,
        x: 0.3,
        y: 0.3
    )
)
let url = client.imageURL(image)
    .width(30)
    .height(100)
    .URL()

// => "https://cdn.sanity.io/images/zp7mbokg/production/Tb9Ew8CXIwaY6R1kjMvI0uRR-2000x3000.jpg?rect=240,300,720,2400&w=30&h=100"

Note that a SanityClient is used here but this operation will not result in a network call. The projectId and dataset name is needed to generate asset URL.

swift-sanity's People

Contributors

sgulseth avatar runeb avatar euwars avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.