🏇 A Swift HTTP / HTTPS networking library just incidentally execute on machines

Overview


Thus, programs must be written for people to read, and only incidentally for machines to execute.
Harold Abelson, "Structure and Interpretation of Computer Programs" ( S.I.C.P )

Pitaya is a Swift HTTP / HTTPS networking library for people. Inspired by Alamofire and JustHTTP.


中文简介

Example

Simple

Pita.build(HTTPMethod: .GET, url: "https://httpbin.org/get?hello=Hello%20Pitaya!")
    .responseJSON { (json, response) -> Void in
        print(json["args"]["hello"].stringValue) // get "Hello Pitaya!"
}

All examples

All Examples

Documentation

Read the documentation

中文文档

Features

  • Support Swift Package Manager
  • Elegant APIs for people
  • Support HTTP Basic Authorization
  • Support setting SSL pinning
  • Support setting HTTP raw body (include JSON body)
  • Asynchronous & Queue
  • Upload files fast
  • Internal fully JSON support with JSONNeverDie
  • Support setting custom HTTP headers
  • almost 100% tested

Requirements

  • iOS 7.0+
  • Xcode 10.2 (Swift 5) (v4.x) in the default swift5 branch.
  • Xcode 9 (Swift 4) (v3.x) in swift4 branch.
  • Xcode 8 (Swift 3) (v2.x) in swift3 branch.
  • Xcode 7 (Swift 2) (v1.x) in master branch.
  • Xcode 6.4 (Swift 1.2) before v0.2.3

Installation

Swift Package Manager

You can use The Swift Package Manager to install Pitaya by adding the proper description to your Package.swift file:

import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    targets: [],
    dependencies: [
        .Package(url: "https://github.com/johnlui/Pitaya.git", versions: "1.3.4" ..< Version.max)
    ]
)

Note that the Swift Package Manager is still in early design and development, for more infomation checkout it's GitHub Page

Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate Pitaya into your Xcode project using Carthage, specify it in your Cartfile:

github "JohnLui/Pitaya"

Then fetch and build Pitaya:

carthage update

At last, add it to "Embedded Binaries" in the general panel use the "Add Other..." button. The Pitaya.framework binary file is lying in ./Carthage/Build/iOS directory.

Manually

git submodule add https://github.com/johnlui/Pitaya.git
open .

then drag Pitaya.xcodeproj into your Project, that's it!

If you want to run your project on devices with Pitaya, just go to PROJECT->TARGETS->[your project name]->General->Embedded Binaries, click +, select Pitaya.frameWork and click "Add".

Source File

Clone all files in the Source directory into your project.

Contribution

You are welcome to fork and submit pull requests.

License

Pitaya is open-sourced software licensed under the MIT license.

中文介绍

Thus, programs must be written for people to read, and only incidentally for machines to execute.(代码是写给人看的,只是恰好能运行。)

Harold Abelson, "Structure and Interpretation of Computer Programs" ( S.I.C.P )

Pitaya(火龙果) 是一个写给人看的纯 Swift 写成的 HTTP / HTTPS 网络库。从 AlamofireJustHTTP 偷了一些创意和代码。

使用示例

基本用法

Pita.build(HTTPMethod: .GET, url: "https://httpbin.org/get?hello=Hello%20Pitaya!")
    .responseJSON { (json, response) -> Void in
        print(json["args"]["hello"].stringValue) // get "Hello Pitaya!"
}

所有用法

All Examples

中文文档

功能

  • 支持 Swift Package Manager
  • 写给人用的优雅 API
  • 支持 HTTP Basic Authorization
  • 支持设置 SSL 钢钉,防“中间人攻击”
  • 支持设置 HTTP raw body (支持 JSON body)
  • 异步、队列
  • 快速文件上传
  • 内置 JSONNeverDie,完全支持 JSON 数据
  • 支持设定 HTTP headers
  • 几乎 100% 测试率

环境要求

  • iOS 7.0+
  • Xcode 10.2 (Swift 5) v4.x 版,位于 swift5 分支(当前默认版本)
  • Xcode 9 (Swift 4) v3.x 版,位于 swift4 分支
  • Xcode 8 (Swift 3) v2.x 版,位于 swift3 分支
  • Xcode 7 (Swift 2) v1.x 版,位于 master 分支
  • Xcode 6.4 (Swift 1.2) 版: v0.2.3

安装

Swift Package Manager

The Swift Package Manager 是苹果伴随 Swift 开源而推出的 Swift 语言包管理工具。

编辑你项目的 Package.swift

import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    targets: [],
    dependencies: [
        .Package(url: "https://github.com/johnlui/Pitaya.git", versions: "1.3.4" ..< Version.max)
    ]
)

Swift Package Manager 依然在开发中,功能不太稳定,建议关注它的 GitHub Page

Carthage

Carthage 是一个去中心化的 Cocoa 应用程序自动依赖添加工具。

使用以下命令安装 Carthage

$ brew update
$ brew install carthage

安装好 Carthage 后,将下列内容加入你项目的 Cartfile:

github "JohnLui/Pitaya"

自动下载、编译 Pitaya:

carthage update

最后,在 general panel 里 的 "Embedded Binaries" 项下点击 "Add Other..." 按钮,Pitaya.framework 已经躺在了 ./Carthage/Build/iOS 目录里。

这种方法目前还不支持 BITCODE,如果需要支持,请直接将 Pitaya.xcodeproj 拖入你的工程。

手动安装

git clone https://github.com/johnlui/Pitaya.git
open Pitaya

在打开的 Finder 窗口中把 Pitaya.xcodeproj 拖到 Xcode 你的文件树里。

真机调试还需要额外的一步:打开 PROJECT->TARGETS->[your project name]->General,找到 Embedded Binaries, 点击 +, 选中 Pitaya.framework,点击“Add”即可。

源代码安装

Source 文件夹下的文件拖进你的文件树里即可。

参与开源

欢迎提交 issue 和 PR,大门永远向所有人敞开。

开源协议

本项目遵循 MIT 协议开源,具体请查看根目录下的 LICENSE 文件。

Comments
  • 图片上传问题

    图片上传问题

    请教一下,上传文件时候,接口要求提交的参数:client_type、token、class_id、file,然后我的写法如下,但返回结果告诉我说file参数为空,请问正确的写法应该是怎么样的?求大神指导一下 比如: let file = File(name: "file", data: imageData, type: "png") let url = Interface_YiStore + "StoreCenter_Album.Images"

    var params = ["client_type": ios, "token": AppPublic().userData.token] params.updateValue(String(id), forKey: "id")

    let pita = Pita.build(HTTPMethod: .POST, url: url).addFiles([file]).addParams(params) pita.onNetworkError({ (error) in print("error:(error.localizedDescription)") }) pita.responseJSON { (json, response) in print(json) }

    opened by kuangtao22 8
  • 关于上传图片

    关于上传图片

    之前使用的是 Alamofire ,现在迁到 Pitaya 了

    之前是这样上传图片的:

    private lazy var uploadImages = [UIImage]()
    .
    .
    .
            Alamofire.upload(
                .POST,
                url,
                multipartFormData: { multipartFormData in
    
                    for i in 0 ..< self.uploadImages.count {
                        let img = self.uploadImages[i]
                        multipartFormData.appendBodyPart(data: UIImageJPEGRepresentation(img, UPLOAD_IMG_QULITY)!, name: "file\(i)", fileName: "file\(i).jpg", mimeType: "image/jpeg")
                    }
            }
    

    而Pitaya中上传图片的接口是

    Pitaya.build(HTTPMethod: HTTPMethod.POST, url: url)
                    .addFiles(<#T##files: [File]##[File]#>)
    
    

    setHTTPBodyRaw 只能是字符串类型

    该如何解决这个问题呢?谢谢

    opened by tooodooo 7
  • 更新版本后忽略了请求参数值必须是String类型的?

    更新版本后忽略了请求参数值必须是String类型的?

    b76e70c93c13d4f50aa6c480262094eeb7219c03 这次更改对拼接参数的值做了限制,只能是String类型的,导致在addParams中传入非String类型的值的参数被忽略过滤掉了

    // Helper.swift
        // stolen from Alamofire
        static func buildParams(_ parameters: [String: Any]) -> String {
            var components: [(String, String)] = []
            for key in Array(parameters.keys).sorted(by: <) {
                let value = parameters[key]
                components += Helper.queryComponents(key, value)
            }
    
            return components.map{"\($0)=\($1)"}.joined(separator: "&")
        }
        // stolen from Alamofire
        static func queryComponents(_ key: String, _ value: Any) -> [(String, String)] {
            var components: [(String, String)] = []
            if let valueString = value as? String {
                components.append(contentsOf: [(Helper.escape(key), Helper.escape(valueString))])
            }
            return components
        }
    

    而之前的版本是这样的:

        static func buildParams(_ parameters: [String: AnyObject]) -> String {
            var components: [(String, String)] = []
            for key in Array(parameters.keys).sorted(by: <) {
                let value: AnyObject! = parameters[key]
                components += Helper.queryComponents(key, value)
            }
    
            return components.map{"\($0)=\($1)"}.joined(separator: "&")
        }
        // stolen from Alamofire
        static func queryComponents(_ key: String, _ value: AnyObject) -> [(String, String)] {
            var components: [(String, String)] = []
            components.append(contentsOf: [(Helper.escape(key), Helper.escape("\(value)"))])        
            return components
        }
    
    

    请问这样改了是因为?

    opened by wuyongrui 5
  • 倒入项目遇到的一些问题

    倒入项目遇到的一些问题

    Pitaya是通过git方法手动倒入的。在项目中import Pitaya都没有任何的问题。可是调用

     Pita.build(HTTPMethod: .GET, url: "https://httpbin.org/get?hello=Hello%20Pitaya!")
        .responseJSON { (json, response) -> Void in
            print(json["args"]["hello"].stringValue) // get "Hello Pitaya!"
    }
    

    就会提示有错误

    Undefined symbols for architecture x86_64:
      "JSONNeverDie.JSONND.stringValue.getter : Swift.String", referenced from:
          WeatherQ.ViewController.(viewDidLoad (WeatherQ.ViewController) -> () -> ()).(closure #1) in ViewController.o
      "JSONNeverDie.JSONND.subscript.getter : (Swift.String) -> JSONNeverDie.JSONND", referenced from:
          WeatherQ.ViewController.(viewDidLoad (WeatherQ.ViewController) -> () -> ()).(closure #1) in ViewController.o
    ld: symbol(s) not found for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    
    

    不知道是什么问题。谢谢解答。

    opened by dowhilenet 4
  • 这个错误是不是你写的问题呀

    这个错误是不是你写的问题呀

    2015-12-10 20:46:39.744 Demo[18851:6808171] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Demo.SearchItemResult)'

    opened by jackson1st 3
  • File 添加 Date 属性,方便直接上传 NSData 文件

    File 添加 Date 属性,方便直接上传 NSData 文件

    可以使用该方法来直接上传 NSData

    let image = UIImage(named: "test")
    let data  = UIImageJPEGRepresentation(image!, 0.9)
    let file = File(name: "123", data: data!,type: "jpg")
    
    opened by BrikerMan 0
  • "Invalid or missing Program/ProgramArguments"

    I am testing on OS X EI Captian xcode 7.01, when I run the project, an alert pops up and says:"Invalid or missing Program/ProgramArguments". I tried several ways, such as redownload the zip file from github, restart Xcode, clear derived data for project, clean build folder, to solve it but failed.

    Anyone knows why this happens?

    Thanks a lot.

    opened by AniOSDeveloper 0
  • 升级xocde10 以后

    升级xocde10 以后

    Showing All Messages :-1: Multiple commands produce '/Users/lcr/Library/Developer/Xcode/DerivedData/test-aszthffiswmwkgfkwkmsotxazari/Build/Products/Debug-iphonesimulator/Pitaya/Pitaya.framework/Info.plist':

    1. Target 'Pitaya' (project 'Pods') has copy command from '/Users/lcr/Desktop/test/Pods/Pitaya/Pitaya/Info.plist' to '/Users/lcr/Library/Developer/Xcode/DerivedData/test-aszthffiswmwkgfkwkmsotxazari/Build/Products/Debug-iphonesimulator/Pitaya/Pitaya.framework/Info.plist'
    2. Target 'Pitaya' (project 'Pods') has process command with output '/Users/lcr/Library/Developer/Xcode/DerivedData/test-aszthffiswmwkgfkwkmsotxazari/Build/Products/Debug-iphonesimulator/Pitaya/Pitaya.framework/Info.plist'
    opened by llouoll 0
  • Unable to use Pitaya's carthage installation with Xcode 8.3

    Unable to use Pitaya's carthage installation with Xcode 8.3

    Getting following compile time error: Module compiled with Swift 3.0.2 cannot be imported in Swift 3.1: .../Carthage/Build/iOS/Pitaya.framework/Modules/Pitaya.swiftmodule/x86_64.swiftmodule

    Have tried using the following terminal commands: carthage update --platform iOS --no-use-binaries and Carthage update --platform iOS --no-use-binaries --toolchain com.apple.dt.toolchain.Swift_3_1

    Also tried removing derived data and installing the framework again.

    Branch: Swift3 Cart file text: github "JohnLui/Pitaya" "swift3" Xcode version: 8.3

    Only able to use Pitaya in above scenario, if it is first compiled as a library project and then the framework product is imported as an embedded library.

    opened by speedoholic 0
Releases(v4.0.1)
Owner
John Lui
John Lui
ServiceData is an HTTP networking library written in Swift which can download different types of data.

ServiceData Package Description : ServiceData is an HTTP networking library written in Swift which can download different types of data. Features List

Mubarak Alseif 0 Nov 11, 2021
QwikHttp is a robust, yet lightweight and simple to use HTTP networking library for iOS, tvOS and watchOS

QwikHttp is a robust, yet lightweight and simple to use HTTP networking library. It allows you to customize every aspect of your http requests within a single line of code, using a Builder style syntax to keep your code super clean.

Logan Sease 2 Mar 20, 2022
Elegant HTTP Networking in Swift

Alamofire is an HTTP networking library written in Swift. Features Component Libraries Requirements Migration Guides Communication Installation Usage

Alamofire 38.7k Jan 8, 2023
Versatile HTTP Networking in Swift

Net is a versatile HTTP networking library written in Swift. ?? Features URL / JSON / Property List Parameter Encoding Upload File / Data / Stream / M

Intelygenz 124 Dec 6, 2022
Simple asynchronous HTTP networking class for Swift

YYHRequest YYHRequest is a simple and lightweight class for loading asynchronous HTTP requests in Swift. Built on NSURLConnection and NSOperationQueue

yayuhh 77 May 18, 2022
Easy HTTP Networking in Swift a NSURLSession wrapper with image caching support

Networking was born out of the necessity of having a simple networking library that doesn't have crazy programming abstractions or uses the latest rea

Nes 1.3k Dec 17, 2022
Extensible HTTP Networking for iOS

Bridge Simple Typed JSON HTTP Networking in Swift 4.0 GET GET<Dict>("http://httpbin.org/ip").execute(success: { (response) in let ip: Dict = respo

null 90 Nov 19, 2022
🤵🏽‍♀️ Janet — A thin HTTP networking layer built on URLSession for simple, declarative endpoint specification leveraging the power of async/await.

????‍♀️ Janet — Just another networking kit — A thin HTTP networking layer built on URLSession for simple, declarative endpoint specification leveragi

Niklas Holloh 3 Sep 6, 2022
Http - Demo for Http Layer

http Example To run the example project, clone the repo, and run pod install fro

null 0 Jan 24, 2022
RSNetworking is a networking library written entirly for the Swift programming language.

RSNetworking is a networking library written entirly for the Swift programming language.

null 18 Feb 25, 2018
A networking library for Swift

Nikka Nikka is a super simple Swift HTTP networking library that comes with many extensions to make it modular and really powerful. Installation Usage

Emilien Stremsdoerfer 29 Nov 4, 2022
AsyncHTTP - Generic networking library written using Swift async/await

Generic networking library written using Swift async/await

Laszlo Teveli 7 Aug 3, 2022
Malibu is a networking library built on promises

Description Palm trees, coral reefs and breaking waves. Welcome to the surf club Malibu, a networking library built on promises. It's more than just a

Vadym Markov 410 Dec 30, 2022
Asynchronous socket networking library for Mac and iOS

CocoaAsyncSocket CocoaAsyncSocket provides easy-to-use and powerful asynchronous socket libraries for macOS, iOS, and tvOS. The classes are described

Robbie Hanson 12.3k Jan 8, 2023
foursquare iOS networking library

FSNetworking foursquare's iOS networking library FSN is a small library for HTTP networking on iOS. It comprises a single class, FSNConnection, and se

Foursquare 386 Sep 1, 2022
Swish is a networking library that is particularly meant for requesting and decoding JSON via Decodable

Swish Nothing but net(working). Swish is a networking library that is particularly meant for requesting and decoding JSON via Decodable. It is protoco

thoughtbot, inc. 369 Nov 14, 2022
Malibu is a networking library built on promises

Description Palm trees, coral reefs and breaking waves. Welcome to the surf club Malibu, a networking library built on promises. It's more than just a

HyperRedink 10 Jan 29, 2022
A networking library for iOS, macOS, watchOS and tvOS

Thunder Request Thunder Request is a Framework used to simplify making http and https web requests. Installation Setting up your app to use ThunderBas

3 SIDED CUBE 16 Nov 19, 2022
A resource based, protocol oriented networking library designed for pure-SwiftUI applications.

Monarch ?? - WIP A resource based, protocol oriented networking library designed for pure-SwiftUI applications. Features: Async/Await Resource Based P

Emilio Pelaez Romero 4 Oct 17, 2022