Giter Site home page Giter Site logo

freshos / ws-deprecated Goto Github PK

View Code? Open in Web Editor NEW
353.0 11.0 32.0 30.36 MB

⚠️ Deprecated - (in favour of Networking) :cloud: Elegantly connect to a JSON api. (Alamofire + Promises + JSON Parsing)

License: MIT License

Objective-C 1.02% Swift 96.93% Ruby 2.06%
networking http swift json promise ios httpclient rest rest-api micro-framework

ws-deprecated's Introduction

Try it!

Download our starter iOS Project and see how our tools fit together in a typical iOS App:
Download Starter Project

Our mission

FreshOS is on a mission to provide iOS developers with simple tools to solve problems that 99% of us have. We believe developers should focus on valuable things like app logic, rather than casting the values of a JSON Parsing \o/. We thrive to make apis as simple as possible, yet flexible enough to handle 99% of use-cases. We believe in Unix-style libraries, that do one thing and do it well. Since we have control over those tools, they fit together nicely.

Solutions

AutoLayout - Stevia 🍃 Star

Write expressive autolayout code, readable and maintainable

Networking - ws ☁️ Star

Write concise networking code that leverages the power of Alamofire, promises and JSON Parsing

Async - then 🎬 Star

Make Async code delightful with Promises

Write minimalist JSON Parsing that infers type and doest get in the way of your models

Reduce Stress & Errors

Emit warnings and errors when Localizations are missing or unused

Emit warnings and errors when assets are missing or unused

Integrate Faster

Generate Swift code from Sketch designs

Who we are

<script src="//cdn.jsdelivr.net/github-cards/latest/widget.js"></script>
<script src="//cdn.jsdelivr.net/github-cards/latest/widget.js"></script> Let's not forget the 100+ people that contributed via pull requests, issues or even just talking to them :) This wouldn't be possible without them <3

Production ready

Our libraries have been Downloaded 175k+ times and already more than 3700+ Apps use freshOS tools!

Source : Cocoapods

Testimonials <3

Sketch to Swift is an amazing way to build quick prototypes. Always using to build small samples for my freelancing clients. Also using AssetChecker so I'm never messing up and breaking my code because I deleted or changed the name of an asset. I appreciate the work they put in freshOS and I'm glad AwesomeiOS has all of them
Lucas Farah - Admin @Awesome-iOS

Just want to say I love your different solutions. It's smart clean and easy to use.
Florent Douine - iOS Developer

Man I just wanted to tell you that Stevia, then, Arrow and ws is the most beautiful thing ever made! Really! This is beautiful!
Mauran Muthiah - Developer

This kind of libraries really is perfect. Very focused, obviously simple and useful, no magic, and small. They make development easier one step at a time.
Anonymous - HackerNews

Support/Contact

You can raise a github issue on the project you need support with or contact us at [email protected]

Hosting sponsored with 💚 by Muxu.Muxu

<script async defer src="https://buttons.github.io/buttons.js"></script>

ws-deprecated's People

Contributors

adolfo avatar andreirt avatar brian-dlee avatar ezisazis avatar f2m2rd avatar maxkonovalov avatar n13 avatar pafgz avatar s4cha avatar stami avatar tmcw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ws-deprecated's Issues

Support keypath in typed calls

Hey @s4cha!
What do you think of adding a resource keypath in ws calls? It's similar to what is implemented in RestKit objects mapping.

Consider the following server response:

{
     count: 2,
     articles: [
          {
               id: 1,
               name: "Foo"
          },
          {
               id: 2,
               name: "Bar"
          }
     ],
     error: 
          { 
               code: 0,
               message: "Test" 
          }
}

It would be great to be able to parse it like this:

ws.get("/articles", params: ["category": name], keypath: "articles").then { articles in 
    // articles = ["Foo", "Bar"]
}.onError { error in 
    // error = "Test"
}

I am aware of the jsonParsingSingleResourceKey and jsonParsingColletionKey, they seem to fulfil the need partially, but if the key is different for different calls, it requires additional setup to be made.
As for response error handling, its mapping description could be added globally to WS class similar to jsonParsingSingleResourceKey, specifying the keypath and maybe a custom error class or something like this to be able to parse the specific error format returned by server.

Currently it requires to write a wrapper function like this:

func get<T: ArrowParsable>(path: String, params: [String: AnyObject] = [:], keypath: String? = nil) -> Promise<T> {
    return Promise<T>(callback: { (resolve, reject) in
        ws.get(path, params: params)
            .then({ (json: JSON) in
                if let error = NSError(json: json) {
                    reject(error)
                } else {
                    resolve(self.modelFromJSON(json, key: keypath))
                }
            })
            .onError({ (error) in
                reject(error)
            })
    })
}

How to get json returned when server response is 422 ?

Hi,
I'm calling a rest api and the server is returning server response 422, but the error I'm getting in the onError block shows 'unknown' with message '-1 - Unknown'

The log shows:

200 'https://myapi.com/'
responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

When I run the api in swagger the json returned is:

{
  "message": "The selected email is invalid.",
  "errors": [
    {
      "name": "email",
      "desc": "The selected email is invalid."
    }
  ]
}

and the headers shown are:

 access-control-allow-credentials: true 
 access-control-allow-headers: X-Platform, Content-Type, X-Auth-Token, Origin, Authorization, X-Requested-With, x-xsrf-token 
 access-control-allow-methods: GET, POST, PUT, DELETE, OPTIONS 
 access-control-allow-origin: http://subbyfinder.naamtechstaging.com 
 cache-control: no-cache, private 
 connection: keep-alive 
 content-type: application/json 
 date: Wed, 20 Jun 2018 05:04:23 GMT 
 server: nginx/1.10.3 (Ubuntu) 
 transfer-encoding: chunked 

Thanks,
WS is great and thanks for all your efforts.

Handle double parameters for multipart request

I send a multipart request with a picture and other parameters. The string ones work but the Double ones don't. I checked the file WSRequest.swift in method func sendMultipartRequest(_ resolve: @escaping (_ result: (Int, [AnyHashable: Any], JSON)) -> Void, reject: @escaping (_ error: Error) -> Void, progress:@escaping (Float) -> Void)

I add the double case like this :

for (key, value) in self.params {
	if let int = value as ? Int {
		let str = "\(int)"
		if let d = str.data(using: String.Encoding.utf8) {
			formData.append(d, withName: key)
		}
	} else if
	let double = value as ? Double {
		let str = "\(double)"
		if let d = str.data(using: String.Encoding.utf8) {
			formData.append(d, withName: key)
		}
	} else {
		if let str = value as ? String, let data = str.data(using: String.Encoding.utf8) {
			formData.append(data, withName: key)
		}
	}
}

Would be cool if you could fix it officially

Method Post return value

One question. I have problem with post

ws.post("/api/add_action", params: ["user":"sasdas"]).then { json in
print(json["id"])
}

Error compilation

Ambiguos use of 'get(_:params:)'

I upgrade with carthage update and run code error

ws.WS:26:17: note: found this candidate
    public func get(url: String, params: [String : AnyObject] = default) -> then.Promise<Arrow.JSON>
                ^
ws.WS:30:17: note: found this candidate
    public func get(url: String, params: [String : AnyObject] = default) -> then.Promise<Void>

Upload App Store Unsupport arm64

I use ws 1.1.5

I can not upgrade to 1.3, because It stops working because all my application, I prefer to only use this version

Cartfile.resolved

github "Alamofire/Alamofire" "3.2.1"
github "s4cha/Arrow" "0.7.6"
github "stephencelis/SQLite.swift" "0.10.1"
github "s4cha/then" "2.0.1"
github "s4cha/ws" "1.1.5"

I use command carthage update

Carthage/Checkouts/ws/ws/WS.swift:13:8: error: module file was created by a newer version of the compiler: /Carthage/Checkouts/ws/Carthage/Build/iOS/then.framework/Modules/then.swiftmodule/arm64.swiftmodule
A shell task (/usr/bin/xcrun xcodebuild -project //Carthage/Checkouts/ws/ws.xcodeproj -scheme ws -configuration Release -sdk iphoneos ONLY_ACTIVE_ARCH=NO BITCODE_GENERATION_MODE=bitcode CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES clean build) failed with exit code 65:
** BUILD FAILED **

Old projects this version was used
github "s4cha/then" "1.4.0"

with ws 1.1.5, now automatically change to
github "s4cha/then" "2.0.1"

why?

WS really supports ios 8+?

source podfile:

platform :ios, '8.0'

target 'App' do

pod 'ws', '~> 2.0'
use_frameworks!
end

run pod install

Error:

[!] Unable to satisfy the following requirements:

  • ws (~> 2.0) required by Podfile

Specs satisfying the ws (~> 2.0) dependency were found, but they required a higher minimum deployment target.

Log levels

Hey, great framework, I really enjoy using it :)
Would be nice though to add logging levels or at least an ability to temporarily disable the console logs for ws.
Also the same response is printed twice if Promise with custom model object is returned, which seems unnecessary.

Accessing AF's response validation

I pass a custom Accept header to my API but it's throwing Alamofire.AFError.ResponseValidationFailureReason.unacceptableContentType error and I don't see AF exposed anywhere for me to add to the allowed content types validation array.

Anyone have any suggestions?

Regression regarding `resolveOnMainThread `

Obviously, this is not a bug per se, but it is worth noting that v2.0.3 breaks a lot of existing code by deallocating prematurely when the first promise is not retained manually (for example in nested functions)... Something like:

func fetchData() {
	
	showLoading()
	
	func fetch() -> Promise<Something> {
		...
	}
	
	fetch().resolveOnMainThread()
	.then { data in
		...
	}
	.onError { error in
		...
	}
	.finally { [weak self] in
		self?.hideLoading()
	}
	
}

Extending PUT

Hello Sacha,

Loving this library so far :-).

I'm quite a n00b to this and was hoping you could help me out with extending one of the functions:

What I essentially need is to extend ws.put to take different parameters, instead of
params: [String : AnyObject], I would like it to take params: [String : Any]

I looked in the WS+Requests.swift but couldn't get it to work because the returned call function doesn't exist.

Reason I need this is because when I PUT a boolean as paramater, the AnyObject returns a 0 or a 1, while the API that I am putting to only takes true or false. The API i'm posting to is the philips Hue 2.0 bridge.

Looking very much forward to your replay :).

Kind Regards,

Andre Vink

REFRESH REQUEST

Hi,
When interacting with OAuth Transparent token refresh is almost always desired.

As WS stands on the shoulder of Alamofire, and Alamofire v4 supports a new RequestRetrier protocol,
how can I configure WS so that when my authentication token expires I get a new one and retry the request?

Thanks!

Usage in an extension

Getting this when trying to use inside an extension
'shared' is unavailable in application extensions for iOS: Use view controller based solutions where appropriate instead.

I comment out everything in that function and it compiles fine

    func tick() {
//        let previousValue = UIApplication.shared.isNetworkActivityIndicatorVisible
//        let newValue = (runningRequests > 0)
//        if newValue != previousValue {
//            UIApplication.shared.isNetworkActivityIndicatorVisible = newValue
//        }
    }

POST params as JSON?

How can I serialize POST params as JSON?

Let's say we have save() like this

func save() -> Promise<MyModel> {
    return ws.post("/mymodels", params: ["data": ["date": startingDate, "number": 123]])
}

Log output is

POST /mymodels
params : ["data": {
    date = "2016-04-21 18:26:53 +0000";
    number = 123;
}]
CODE: 400

So params should be something like

{
  "data": {
    "date" = "2016-04-21 18:26:53 +0000",
    "number" = 123
  }
}

Can this be accomplished easily with ws, or should I be looking for alternatives or plain Alamofire?

SPM package is broken for Xcode12

Hi there,
since Xcode12 drops support for iOS8, ws fails to build on Xcode12 with the following error:

Target Integrity:
The package product 'Alamofire' requires minimum platform version 9.0 for the iOS platform, but this target supports 8.0

Are you planning an updated version/branch with iOS9 deployment target, or would be safe to fork and link edited/forked version in the project (I understand that there is a new, successor to this project) ?

Post promise error

Hi, first, thanks for your good job! (especially with Stevia 👍 )

I wanted to use your lib (v2.0.4) to post some datas but...

When I try this:

import Arrow
import then
import ws

let ws = WS("")
ws.post("", params: ["":""]).then { json in }

Produce error: Ambiguous use of 'post(_:params:)'

And when used like in the get example:

func test() -> Promise<JSON> {
        return ws.post("", params: ["":""])
}

Produce error: No 'post' candidates produce the expected contextual result type 'Promise'

Any ideas?
Did I miss something?

Tell me if I can help!

Merci :)

Supporting multiple multipart data

How can I request with multiple multipart data. As i can see that existing methods doesn't seems to be providing this. Am I missing something?

In WS.Swift file
open func postMultipart(_ url: String,
params: Params = Params(),
name: String,
data: Data,
fileName: String,
mimeType: String) -> Promise {
let r = postMultipartRequest(url,
params: params,
name: name,
data: data,
fileName: fileName,
mimeType: mimeType)
return r.fetch().resolveOnMainThread()
}

and request in WS+Requests.swift

public func postMultipartRequest(_ url: String,
params: Params = Params(),
name: String,
data: Data,
fileName: String,
mimeType: String) -> WSRequest {
let c = call(url, verb: .post, params: params)
c.isMultipart = true
c.multipartData = data
c.multipartName = name
c.multipartFileName = fileName
c.multipartMimeType = mimeType
return c
}

Carthage frameworks

There are errors when submitting an archive that contains ws framework added via Carthage:

screen-shot-2

This is caused by ws.framework containing its own Frameworks folder. I guess, that's because of the "Run Script" build phase included in ws target, which also results in including then.framework twice when submitting the build:

screen-shot-1

I worked around the issue by adding a "Run Script" build phase in the host app's target to remove the nested "Frameworks" folder:

cd "${SRCROOT}/Carthage/Build/iOS/ws.framework"
if [[ -d "Frameworks" ]]; then
rm -fr Frameworks
fi

But it would be great if it could be fixed directly in the framework 😉

Auth Header Bearer Token refresh, AF5 beta

Before each call, I need to check if my bearer token is still OK, and if not get a new one, and then set it in the headers.

I looked into the code, it will be trivial to add a RequestAdapter to ws - as supported by Alamofire 4 - and that could do that except not asynchronously. So I'd still get occasional errors when the token isn't refreshed in time. And I'd have to deal with those errors on a code level which kind of destroys the elegance and simplicity of using ws.

AlamoFire 5 has a built in solution for this exact problem.

I have two questions

  • Has anybody looked into upgrading to AlamoFire 5 (currently in beta)? That would allow for asynchronous bearer token refresh, making what I need trivial to implement. They added a callback to RequestAdapter - super easy to use.

  • Is there another good way you can think of to provide a feature similar to AF5 callback based RequestAdapter? Didn't really see one...

As ws library is concerned upgrading to AF5 is probably the best way to go about it.

Parameter Encoding in WSRequest

I am using WS to send requests to an API, and my request always fails when the verb is DELETE.

I have digged into it and the reason is that for the DELETE requests the parameters Encoding is always set to "URLEncoding.default", even if in my implementation I try to pass a different one.

In the method is buildRequest() in the WSRequest.swift file, there is this code which sets the encoding to URLEncoding.default for anything else than POST or PUT:

var request: URLRequest?
if httpVerb == .post || httpVerb == .put {
request = try? postParameterEncoding.encode(r, with: params)
} else {
request = try? URLEncoding.default.encode(r, with: params)
}
return request ?? r

I have change this to the following:

var request: URLRequest?
if httpVerb == .post || httpVerb == .put || httpVerb == .delete {
request = try? postParameterEncoding.encode(r, with: params)
} else {
request = try? URLEncoding.default.encode(r, with: params)
}
return request ?? r

And now the DELETE requests work fine.

However when I'll download future updates I'll have to do it again.

Would it not be better to just have this:

var request: URLRequest?
request = try? postParameterEncoding.encode(r, with: params)
return request ?? r

And let the user pass the encoding needed?

Thanks

When will swift5 be supported?

When I tried to use the ws framework, I found that it relied on Then and Arrow libraries, but neither of them supported swift5. Now that swift5 has been released for so long, I really hope to update it to support swift5 soon. Thanks.

Cannot call any api call,keep getting ambiguous argument error in compile time

    let w = WS("http://localhost:4000/api")
    let result = w.get("test",params: [:])

getting me
Ambiguous use of 'get(_:params:)'

    let w = WS("http://localhost:4000/api")
    let result = w.get("test")

with a error of
/Users/misuzi/developing/ios/dream_garden_manage/dream_garden_manage/Login.swift:124:22: Ambiguous use of 'get(_:params:)'

    let w = WS("http://localhost:4000/api")
    let result = w.post("test",params: ["name": "123"])

/Users/misuzi/developing/ios/dream_garden_manage/dream_garden_manage/Login.swift:124:22: Ambiguous use of 'post(_:params:)'

I'm using pod to install ws 2.0.0 and swift 3.0

Any suggestions?

Please update version 3.1.0 on Cocoapods

Hi,

I'm using this lib in my current project.
But when updated to xCode 9.3, my code got a bug:
Ambiguous use of 'init(callback:)' in thenPromise lib
I see you have updated to version 3.1.0 to support xCode 9.3 and Swift 4.1 but looks like it has not been updated on Cocoapods yet

[!] CocoaPods could not find compatible versions for pod "ws":
  In Podfile:
    ws (~> 3.1.0)

None of your spec sources contain a spec satisfying the dependency: `ws (~> 3.1.0)`.

Please help, thank so much for a useful lib

Support for error handling on responses with a 200

Hi there,

Given that is common for a lot of APIs to return valid JSON responses with (business) errors that are described in the body (alà success = false) with a 200 status code, would it be possible maybe to open functions like handleJSONResponse etc in order to override in a subclass and thus rejecting accordingly? (The point being to treat both system & business errors as reason for rejection in a chain)

Unless I am missing some other way to do that transparently...

Any thoughts?

Handle http code

Hello,

I dont find in the README how to get the HTTP code in case of response.

Is it possible ? If yes i think this could be nice to add it in the README :-)

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.