Giter Site home page Giter Site logo

just's Introduction

Supported Flatform CocoaPods Carthage compatible Build Status

Just is a client-side HTTP library inspired by python-requests - HTTP for Humans.

Features

Just lets you to the following effortlessly:

  • URL queries
  • custom headers
  • form (x-www-form-encoded) / JSON HTTP body
  • redirect control
  • multipart file upload along with form values.
  • basic/digest authentication
  • cookies
  • timeouts
  • synchronous / asynchronous requests
  • upload / download progress tracking for asynchronous requests
  • link headers
  • friendly accessible results

Use

The simplest request with Just looks like this:

//  A simple get request
Just.get("http://httpbin.org/get")

The next example shows how to upload a file along with some data:

//  talk to registration end point
let r = Just.post(
    "http://justiceleauge.org/member/register",
    data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
    files: ["profile_photo": .url(fileURLWithPath:"flash.jpeg", nil)]
)

if r.ok { /* success! */ }

Here's the same example done asynchronously:

//  talk to registration end point
Just.post(
    "http://justiceleauge.org/member/register",
    data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
    files: ["profile_photo": .url(fileURLWithPath:"flash.jpeg", nil)]
) { r in
    if r.ok { /* success! */ }
}

Read Getting Started on the web or in this playground to learn more!

Install

Here are some ways to leverage Just.

Xcode

Add https://github.com/dduan/Just.git the usual way.

Swift Package Manager

Add the following to your dependencies:

.package(url: "https://github.com/dduan/Just.git",  from: "0.8.0")

โ€ฆ and "Just" to your target dependencies.

Carthage

Include the following in your Cartfile:

github "dduan/Just"

Just includes dynamic framework targets for both iOS and OS X.

CocoaPods

The usual way:

platform :ios, '8.0'
use_frameworks!

target 'MyApp' do
  pod 'Just'
end

Manual

Drop Just.xcodeproj into your project navigator. Under the General tab of your project settings, use the plus sign to add Just.framework to Linked Framework and Libraries. Make sure to include the correct version for your target's platform.

It's also common to add Just as a git submodule to your projects repository:

cd path/to/your/project
git submodule add https://github.com/dduan/Just.git

Source File

Put Just.swift directly into your project. Alternately, put it in the Sources folder of a playground. (The latter makes a fun way to explore the web.)

Contribute

Pull requests are welcome. Here are some tips for code contributors:

Work in Just.xcworkspace.

The tests for link headers relies on Github APIs, which has a low per-hour limit. To overcome this, you can edit the Xcode build schemes and add environment variables GITHUB_TOKEN. Learn more about personal tokens here.

For Xcode rebels, checkout Makefile.

HTML documentation pages are generated by literate programmin tool docco

License

MIT, see LICENSE.md.

just's People

Contributors

alperkal avatar cipi1965 avatar cryptodevtrader avatar dduan avatar evenbrenna avatar ezfe avatar gtchance avatar heptal avatar mileswd avatar rapidstephan avatar readmecritic avatar rxwei avatar saagarjha avatar saeta avatar zuphilip 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  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

just's Issues

multipart / form-data

How to send ( post ) multipart / form-data? only string data ... not files ... Thanks ...

Compile Error

โžœ  carthage update
*** Cloning Just
*** Checking out Just at "v0.2"
*** Building scheme "Just-iOS" in Just.xcodeproj
** BUILD FAILED **


The following build commands failed:
    CompileSwift normal x86_64 Carthage/Checkouts/Just/Just/Just.swift
    CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler
(2 failures)
A shell task failed with exit code 65:
** BUILD FAILED **


The following build commands failed:
    CompileSwift normal x86_64 Carthage/Checkouts/Just/Just/Just.swift
    CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler
(2 failures)

Send files not as multipart/form-data

Hi,

First of all - thanks for this great library!
I'm trying to post a file to my server, but the server expect an application/zip content, and when i'm trying to send a file using Just it keeps changing the content-description to multipart/form-data.
Is there any way to force it not to change the content-description?

Swift 3 Support

The current version will need to be updated to support Swift 3. When using the framework in a project many errors are thrown.

Elon.jpg

elon.jpg causes a major issue in the code. The level of awesomeness housed in that one file throws the awesomeness levels off in the rest of the code. In order to fix the problem, I would suggest also adding a picture of Nikola Tesla in a different folder. ;)

Just with baseUrl

it seems for every network request I need to rewrite baseUrl. so it is a way to have a shared Just with a base url?

Using Swift 2 doesn't seem to like Just

I got these build issues, any ideas? I'm new to Swift and Xcode and need some help ๐Ÿ˜„
screenshot 2015-09-03 11 54 45

.../Pods/Just/Just/Just.swift:116:23: Expected expression in 'return' statement
.../Pods/Just/Just/Just.swift:748:35: Expected expression in assignment
.../Pods/Just/Just/Just.swift:753:43: Expected expression in assignment
.../Pods/Just/Just/Just.swift:257:22: Use of undeclared type 'LazyMapCollection'
.../Pods/Just/Just/Just.swift:260:24: Use of undeclared type 'LazyMapCollection'
.../Pods/Just/Just/Just.swift:163:21: '[String]' does not have a member named 'forEach'
.../Pods/Just/Just/Just.swift:634:13: '[(String, String)]' does not have a member named 'appendContentsOf'
.../Pods/Just/Just/Just.swift:647:47: '[String]' does not have a member named 'joinWithSeparator'

background mode

Hi, great library. thanks.
i wondering is there any option for keep working when screen goes off while uploading?

Install via Carthage fails

Attempting to give just a whirl, and doesnt seem to install correctly.

*** Building scheme "Just-iOS" in Just.xcodeproj
** BUILD FAILED **

The following build commands failed:
CompileSwift normal x86_64 /Users/dandrews/AppleAppDev/Carthage/Checkouts/Just/Just/Just.swift
CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler
(2 failures)

about the playground

Thanks for your great job! I have a problem about the playground.
the playground provided in this project just use for reading?
We can't run the playground to see the result,right?

Module file was created by a newer version of the compiler

I am using XCode6.4 and I imported JustHTTP/Just library using Carthage. (*** Downloading Just at "v0.3")

Import worked fine and here is a screenshot of my xcodeproj file enter image description here
screen shot 2015-09-08 at 11 34 37 pm

But on this line:

import Just

I am getting this error

Module file was created by a newer version of the compiler
...../Carthage/Build/iOS/Just.framework/Modules/Just.swiftmodule/x86_64.swiftmodule

Can someone advice? Thanks!

macOS - image not found - Just Frameowrk

Why does the following macOS setup give a JustHTTP linker error ?

Steps to recreate linker error:

Create new macOS Command Line app
Run pod init from Terminal
Update the podfile with the below

platform :osx, โ€™10.10โ€™
use_frameworks!

target 'MyApp' do
pod 'Just'
end

Run pod install
Open and Build workspace
Error: dyld: Library not loaded: @rpath/just.framework
Reason: image not found

AT THIS POINT, this error makes sense. You need to go to the Target's / General / Linked Frameworks and Libraries. Then add Just.

Build and run. Same error. Why?

A short summary of what has been tried:

checked developer cert was valid
checked Path of the Just framework pointed to Relative to build products / Projects / Product
Tried manually pulling in project,  git submodule, carthage and cocoapods
Deleted Derived Data
Added Runtime Search Path $(inherited) @executable_path/Frameworks

logout problem ...slow

func logout (completion:@escaping (Any)->()) {

    let urlString = "https://bhmobile.bhtelecom.ba/c/portal/logout"
    
    Just.get(urlString, allowRedirects:false) { r  in
        
        DispatchQueue.main.async(execute: {
                completion(r.description)
        })
    }

Same logout on android (OkHttp library 80ms - 200ms status code 302)
On iOS - 1s (3G) - 5s (Edge) status code 200 but i need status 302
Why ?

Carthage error

Hi, I can't build the project with Carthage:

A shell task (/usr/bin/xcrun xcodebuild -workspace /Users/hkremmin/devel/IOS/GSimpleRelease/Carthage/Checkouts/Just/Just.xcworkspace -scheme Just-OSX -configuration Release CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES clean -showBuildSettings) failed with exit code 66:
xcodebuild: error: Scheme Just-OSX is not currently configured for the clean action.

Carthage version is 0.18.1
OSX 10.12.1
XCode 8.1

Build command is
carthage update --platform ios

Logging

Would be cool if there was a way to add logging so that you can see the request / response url, body, and headers. Or is there any way to do this now?

Something wrong with timeout.

I want to use 'get' for urls in a array. (count maybe > 100)

[urls].foreach { Just.get($0, timeout: 1) { ... } }

All the 'get' will finish in 1 second, the timeout isn't set to each 'get'.

Vsersion: 0.5.1
Xcode: 8 (8A218a)
Swift: 3.0

'String' is not convertable to 'StringLiteralConvertable' - Error

Hi,

I am trying to replace a NSURLSession with Just. I am failing with a basic file upload.

Here is my code

        Just.post(
              urlString
            , files: [
                "filename": HTTPFile.URL(url, nil)
            ]
            , auth: (account.username, account.password)
            ) { (r: HTTPResult) in
                print("***** \(r.statusCode)")
                dump(r.text)
        }

But i cet a compile error 'String' is not convertable to 'StringLiteralConvertable' on the "filename" string in line 4.

screen shot 2015-08-08 at 01 15 28

does someone has an idea?

carthage update fails

Hi,

carthage update with "0.5.2" version fails with following command -

A shell task (/usr/bin/xcrun xcodebuild -workspace /Users/xyz/projects/project-name/Carthage/Checkouts/Just/Externals/Quick/Quick.xcworkspace -scheme Quick-OSX -configuration Release ONLY_ACTIVE_ARCH=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES clean build) failed with exit code 65:

Why is it building Quick?

How to get past this error?

Thanks!

Can't compile on Ubuntu with Vapor.

Hi,
I'm trying to use Just on Ubuntu with Vapor, but has compile error. Maybe it's platform related and can't be supported, I still want to report this issue to let you have sense.

Main steps:

./Sources/Just/Just.swift:99:56: error: downcast from '[String : String]?' to '[String : String]' only unwraps optionals; did you mean to use '!'?
    return (self as? HTTPURLResponse)?.allHeaderFields as? [String: String]
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^   ~~~~~~~~~~~~~~~~
./Sources/Just/Just.swift:181:40: error: incorrect argument label in call (have 'withResponseHeaderFields:for:', expected 'withResponseHeaderFields:forURL:')
      foundCookies = HTTPCookie.cookies(withResponseHeaderFields: headers,
                                       ^
./Sources/Just/Just.swift:209:12: error: cannot convert value of type 'String' to type 'NSString' in coercion
          ($0 as NSString).trimmingCharacters(in: CharacterSet.whitespaces)
           ^~
./Sources/Just/Just.swift:954:21: error: use of unresolved identifier 'DispatchSemaphore'
    let semaphore = DispatchSemaphore(value: 0)
                    ^~~~~~~~~~~~~~~~~


./Sources/Just/Just.swift:994:39: error: use of unresolved identifier 'DispatchTime'
      let timeout = timeout.flatMap { DispatchTime.now() + $0 }
                                      ^~~~~~~~~~~~
./Sources/Just/Just.swift:995:12: error: use of unresolved identifier 'DispatchTime'
        ?? DispatchTime.distantFuture
           ^~~~~~~~~~~~
./Sources/Just/Just.swift:1095:22: error: cannot convert value of type 'NSMutableData' to type 'Data' in coercion
        data: config.data as Data,
              ~~~~~~~^~~~

Hope Just could support Ubuntu with Vapor. Thanks in advance.

Getting error while using Swift Package Manager

Hi,

I created Package.swift file into project directory with the following code in it.

import PackageDescription

let package = Package(
    name: "JustHTTP",
    targets: [],
    dependencies: [
        .Package(url: "https://github.com/JustHTTP/Just.git", majorVersion: 0, minor: 5)
    ]
)

After running swift build in command line I got the following error:

/Users/XYZ/Desktop/SwiftPackageManagerDemo/.build/debug/CHTTPParser.build/module.modulemap:2:14: error: umbrella directory '/Users/XYZ/Desktop/SwiftPackageManagerDemo/Packages/PerfectHTTPServer-2.0.7/Sources/CHTTPParser/include' not found
    umbrella "/Users/XYZ/Desktop/SwiftPackageManagerDemo/Packages/PerfectHTTPServer-2.0.7/Sources/CHTTPParser/include"
             ^
<unknown>:0: error: build had 1 command failures
error: exit(1): /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f /Users/XYZ/Desktop/SwiftPackageManagerDemo/.build/debug.yaml

Whats wrong?

Upload file in background task.

Is there a way to specify in a post request with a big file that the upload should continue in the background even if the app is minimzed?

[OS X] Modifying UI in async request raises exception

I need to reload a NSTableView in the end of some asynchronous request made by Just, however it ends up with the error:

2015-08-14 20:55:01.943 ClassTrackerSwift[35619:2707409] This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes.  This will cause an exception in a future release.
 Stack:(
    0   CoreFoundation                      0x00007fff9341303c __exceptionPreprocess + 172
    1   libobjc.A.dylib                     0x00007fff92fd276e objc_exception_throw + 43
    2   CoreFoundation                      0x00007fff93412eed +[NSException raise:format:] + 205
    3   Foundation                          0x00007fff9395a4f0 _AssertAutolayoutOnMainThreadOnly + 83
    4   Foundation                          0x00007fff93960391 -[NSISEngine optimize] + 49
    5   Foundation                          0x00007fff9397cbb3 -[NSISEngine constraintDidChangeSuchThatMarker:shouldBeReplacedByMarkerPlusDelta:] + 296
    6   Foundation                          0x00007fff9397ca31 -[NSISEngine tryToChangeConstraintSuchThatMarker:isReplacedByMarkerPlusDelta:undoHandler:] + 435
    7   Foundation                          0x00007fff9394fc5d -[NSLayoutConstraint _tryToChangeContainerGeometryWithUndoHandler:] + 482
    8   Foundation                          0x00007fff9394f5c4 -[NSLayoutConstraint _setSymbolicConstant:constant:] + 427
    9   AppKit                              0x00007fff9106e2a8 -[NSView(NSConstraintBasedLayout) _autoresizingConstraints_frameDidChange] + 236
    10  AppKit                              0x00007fff9106dd39 -[NSView setFrameSize:] + 1433
    11  AppKit                              0x00007fff9106d79a -[NSControl setFrameSize:] + 77
    12  AppKit                              0x00007fff911897a1 -[NSTableView setFrameSize:] + 256
    13  AppKit                              0x00007fff9118a288 -[NSTableView tile] + 433
    14  AppKit                              0x00007fff911a36f9 -[NSTableView bounds] + 113
    15  AppKit                              0x00007fff9104a62e -[NSView(NSInternal) _setLayerNeedsDisplayInViewRect:] + 406
    16  AppKit                              0x00007fff9102dbfc NSViewSetNeedsDisplayInRect + 1014
    17  AppKit                              0x00007fff9118953c -[NSTableView _tileAndRedisplayAll] + 231
    18  ClassTrackerSwift                   0x00000001000452f6 _TFC17ClassTrackerSwift14ViewController11fetchDidEndfS0_FTCS_13CourseFetcher7successSb_T_ + 166
    19  ClassTrackerSwift                   0x0000000100046a5f _TTWC17ClassTrackerSwift14ViewControllerS_21CourseFetcherDelegateS_FS1_11fetchDidEndUS1___fQPS1_FTCS_13CourseFetcher7successSb_T_ + 79
    20  ClassTrackerSwift                   0x0000000100043ac4 _TFFC17ClassTrackerSwift13CourseFetcher5fetchFS0_FSST_U_FGSQCS_10HTTPResult_T_ + 14532
    21  ClassTrackerSwift                   0x0000000100043d77 _TTRXFo_oGSQC17ClassTrackerSwift10HTTPResult__dT__XFo_iGSQS0___iT__ + 23
    22  ClassTrackerSwift                   0x000000010003d9c1 _TPA__TTRXFo_oGSQC17ClassTrackerSwift10HTTPResult__dT__XFo_iGSQS0___iT__ + 81
    23  ClassTrackerSwift                   0x0000000100032b70 _TTRXFo_iGSQC17ClassTrackerSwift10HTTPResult__iT__XFo_oGSQS0___dT__ + 32
    24  ClassTrackerSwift                   0x0000000100032a21 _TFFC17ClassTrackerSwift4Just7requestFS0_FTOS_10HTTPMethod9URLStringSS6paramsGVSs10DictionarySSPSs9AnyObject__4dataGS2_SSPS3___4jsonGSqGS2_SSPS3____7headersGS2_SSSS_5filesGS2_SSOS_8HTTPFile_4authGSqT8usernameSS8passwordSS__7cookiesGS2_SSSS_9redirectsSb7timeoutGSqSd_8URLQueryGSqSS_11requestBodyGSqCSo6NSData_20asyncProgressHandlerGSqFGSQVS_12HTTPProgress_T__22asyncCompletionHandlerGSqFGSQCS_10HTTPResult_T___S7_U_FS7_T_ + 321
    25  ClassTrackerSwift                   0x000000010002fb56 _TPA__TFFC17ClassTrackerSwift4Just7requestFS0_FTOS_10HTTPMethod9URLStringSS6paramsGVSs10DictionarySSPSs9AnyObject__4dataGS2_SSPS3___4jsonGSqGS2_SSPS3____7headersGS2_SSSS_5filesGS2_SSOS_8HTTPFile_4authGSqT8usernameSS8passwordSS__7cookiesGS2_SSSS_9redirectsSb7timeoutGSqSd_8URLQueryGSqSS_11requestBodyGSqCSo6NSData_20asyncProgressHandlerGSqFGSQVS_12HTTPProgress_T__22asyncCompletionHandlerGSqFGSQCS_10HTTPResult_T___S7_U_FS7_T_ + 182
    26  ClassTrackerSwift                   0x0000000100032b97 _TTRXFo_oC17ClassTrackerSwift10HTTPResult_dT__XFo_iS0__iT__ + 23
    27  ClassTrackerSwift                   0x000000010002fbf1 _TPA__TTRXFo_oC17ClassTrackerSwift10HTTPResult_dT__XFo_iS0__iT__ + 81
    28  ClassTrackerSwift                   0x0000000100032d90 _TTRXFo_iC17ClassTrackerSwift10HTTPResult_iT__XFo_oS0__dT__ + 32
    29  ClassTrackerSwift                   0x000000010002dbff _TFC17ClassTrackerSwift4Just10URLSessionfS0_FTCSo12NSURLSession4taskCSo16NSURLSessionTask20didCompleteWithErrorGSqCSo7NSError__T_ + 2575
    30  ClassTrackerSwift                   0x000000010002e0f0 _TToFC17ClassTrackerSwift4Just10URLSessionfS0_FTCSo12NSURLSession4taskCSo16NSURLSessionTask20didCompleteWithErrorGSqCSo7NSError__T_ + 96
    31  CFNetwork                           0x00007fff920337c9 __51-[NSURLSession delegate_task:didCompleteWithError:]_block_invoke235 + 62
    32  Foundation                          0x00007fff9394b7e8 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 7
    33  Foundation                          0x00007fff9394b5b5 -[NSBlockOperation main] + 97
    34  Foundation                          0x00007fff9394aa6c -[__NSOperationInternal _start:] + 653
    35  Foundation                          0x00007fff9394a543 __NSOQSchedule_f + 184
    36  libdispatch.dylib                   0x0000000100533d43 _dispatch_client_callout + 8
    37  libdispatch.dylib                   0x0000000100537fb3 _dispatch_queue_drain + 1804
    38  libdispatch.dylib                   0x0000000100539fc0 _dispatch_queue_invoke + 223
    39  libdispatch.dylib                   0x0000000100536f5e _dispatch_root_queue_drain + 666
    40  libdispatch.dylib                   0x0000000100548cd0 _dispatch_worker_thread3 + 106
    41  libsystem_pthread.dylib             0x00007fff9bc49637 _pthread_wqthread + 729
    42  libsystem_pthread.dylib             0x00007fff9bc4740d start_wqthread + 13
)

Having found this
http://stackoverflow.com/questions/28302019/getting-a-this-application-is-modifying-the-autolayout-engine-error
afterwards, however I couldn't solve it as I lack of knowledge about GCD.

As the auto-created log says, it doesn't raise exception (though I wrote it as it does). It enters an infinite loop.

Can't build with Xcode 8 Beta 6

I'm trying to use Just in an iOS 10 message extension. Due to various issues, Cocoapods isn't working for me, so I've tried dropping in Just.swift, but I get a whole mess of compile errors, some I don't feel confident about fixing.

Has Swift 3 syntax changed since your last build?

Timeouts leave threads hanging

I believe I've come across an issue when running requests in many threads (one thread per request) and some (but not all) of them time out.

The timeouts seem to be "honored" but the thread that initiated the request is left waiting for a semaphore: doing some debugging in Xcode's thread view, I noticed all the threads were stuck on this line:

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)

when I changed it to something like:

                        let NSEC: Int64 = {
                            var base: Int64 = 1
                            for _ in 1...9 {
                                base *= 10
                            }
                            return base
                        }()

                        let tint: Int64 = Int64(timeout ?? 10.0)
                        let how_long = dispatch_time(DISPATCH_TIME_NOW, tint * NSEC)

                        dispatch_semaphore_wait(semaphore, how_long)

my code now runs without problem, I can see threads being created then destroyed, and it's now been running for > 1 hour without any issue (it used to just crash and die with a hundred or so of hung threads in a couple of minutes).

If you want, I'd be happy to polish the fix and push a PR?

should methods have @ discardableResult attribute?

In the cases where the operations (put, post, etc) are performed asynchronously, the result is ignored and the manipulation of the result is done in the completion handler. Currently this warning must be silenced manually, but I wonder if the @ discardableResult could be used instead.

Can't get asyncProgressHandler to work with UI components

Hi,
First of all, great library. thanks.
I'm updating UI components in the main thread as recommended but still can't get the UIprogressView work although console print works fine.

What is wrong here?

 Just.post("https://httpbin.org/post",
                   files:["sample": .url(sampleFile, nil)],
                   asyncProgressHandler:{ p in
                       print(p.percent)
                       DispatchQueue.main.async(execute: {
                               self.progressView.setProgress(p.percent, animated: false)
                        })
          })

How to send a request body as this example?

Equivalent Android code is this:

public static void sendPushNotificatonToFirebaseServer(FirebaseNoti firebaseNoti) {
final String KEY = "AAAA7l6A1jI:APA91bH2oUNSdtifz3qE9RAynqSEa3JgkXARdH6tD_3S8cm9--cSU5Qz0-zfgVQ2aTnYWvsypmZv0mMXUBxqa6R8i14sgMeW0HF2B3WlEFRstdQ3HXrvES9mUZk8YfXr82gLEDC8uGQD";
String json = App.gson.toJson(firebaseNoti);
Log.e("SendingPushJSON", json);
RequestBody body = RequestBody.create("application/json; charset=utf-8", json);
final Request request = new Request.Builder()
.url("https://fcm.googleapis.com/fcm/send")
.post(body)
.addHeader("Authorization", "key="+KEY)
.addHeader("Content-Type", "application/json")
.build();

if (Looper.myLooper() == Looper.getMainLooper()) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            executeRequest(request);
        }
    }).start();
} else {
    executeRequest(request);
}

}

Custom headers?

Hey ๐Ÿ˜ฌ
I can see through the code that indeed the library support custom headers, anywhere you can point me in the docs for it? Can't seem to find anything

Receiving JSON array from request

I need to make a request in my app that returns json data in the form
[{key:value, key:value}, {key:value, key:value}].
Any idea of the best way for this? Thanks.

Crash in URLSessionTask didCompleteWithError

I am getting crash:
Thread 10 Crashed:: Dispatch queue: NSOperationQueue 0x7fc41b480ab0 :: NSOperation 0x7fc4214442c0 (QOS: LEGACY)
0 com.app 0x000000010ceec954 0x10ce2d000 + 784724
1 com.app 0x000000010cee7b78 0x10ce2d000 + 764792
2 com.app 0x000000010cee807e 0x10ce2d000 + 766078
3 net.justHTTP.Just 0x000000010d063b5d TFFC4Just4HTTP7requestFTOS_10HTTPMethod9URLStringSS6paramsGVs10DictionarySSPs9AnyObject__4dataGS2_SSPS3___4jsonGSqPS3___7headersGS2_SSSS_5filesGS2_SSOS_8HTTPFile_4authGSqT8usernameSS8passwordSS__7cookiesGS2_SSSS_9redirectsSb7timeoutGSqSd_8URLQueryGSqSS_11requestBodyGSqCSo6NSData_20asyncProgressHandlerGSqFGSQVS_12HTTPProgress_T__22asyncCompletionHandlerGSqFGSQCS_10HTTPResult_T___S7_U_FS7_T + 77
4 net.justHTTP.Just 0x000000010d05aa18 TPA__TTRXFo_oC4Just10HTTPResult_dT__XFo_iS0__iT_ + 56
5 net.justHTTP.Just 0x000000010d05a622 TTSf4dg_g_g_n___TFC4Just4HTTP10URLSessionfTCSo12NSURLSession4taskCSo16NSURLSessionTask20didCompleteWithErrorGSqCSo7NSError__T + 994
6 net.justHTTP.Just 0x000000010d051d25 TToFC4Just4HTTP10URLSessionfTCSo12NSURLSession4taskCSo16NSURLSessionTask20didCompleteWithErrorGSqCSo7NSError__T + 69
7 com.apple.CFNetwork 0x00007fff91941e9a __51-[NSURLSession delegate_task:didCompleteWithError:]_block_invoke167 + 76
8 com.apple.Foundation 0x00007fff864368d7 NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK + 7
9 com.apple.Foundation 0x00007fff86436595 -[NSBlockOperation main] + 100
10 com.apple.Foundation 0x00007fff86434c7a -[__NSOperationInternal _start:] + 654
11 com.apple.Foundation 0x00007fff86430c64 __NSOQSchedule_f + 194
12 libdispatch.dylib 0x00007fff8ef3640b _dispatch_client_callout + 8
13 libdispatch.dylib 0x00007fff8ef3b03b _dispatch_queue_drain + 754
14 libdispatch.dylib 0x00007fff8ef41707 _dispatch_queue_invoke + 549
15 libdispatch.dylib 0x00007fff8ef39d53 _dispatch_root_queue_drain + 538
16 libdispatch.dylib 0x00007fff8ef39b00 _dispatch_worker_thread3 + 91
17 libsystem_pthread.dylib 0x00007fff939074de _pthread_wqthread + 1129
18 libsystem_pthread.dylib 0x00007fff93905341 start_wqthread + 13

CFURLCreateStringByAddingPercentEscapes deprecated in OS X 10.11

'CFURLCreateStringByAddingPercentEscapes' was deprecated in OS X 10.11: Use [NSString stringByAddingPercentEncodingWithAllowedCharacters:] instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent (since each URL component or subcomponent has different rules for what characters are valid).

I believe this could be resolved with something along the lines of:
let allowedCharacters = NSCharacterSet.URLQueryAllowedCharacterSet() object.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters)

Relevant documentation:
func stringByAddingPercentEncodingWithAllowedCharacters(_ allowedCharacters: NSCharacterSet) -> String?
NSCharacterSet Class Reference

Thanks!

Asynchronous Callback

My app crashing using asynchronous callback but works fine when switching to synchronous mode. I dont know why.

Pseudo Sample:
APP CRASHING:
Just.post(
"http://justiceleauge.org/member/register",
data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { r in
if r.ok { /* SOME CODE HERE! */ }
}

THIS WORKS:
let r = Just.post(
"http://justiceleauge.org/member/register",
data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
)

if r.ok { /* SOME CODE HERE! */ }

File Upload issue on PHP Handler (Swift 3 / XCode 8)

Im currently on XCode 8 with Swift 3 and i have a PHP file upload handler in the server side. Using the provided playground file, and basically just changing the POST URL to my PHP handler, upload doesnt work (file not reaching the server) but no error whatsoever. Fyi, i used another swift HTTP client (Swift 2.x version compatible) with the same PHP handler and it is working fine.

From playground:
let elonPhotoURL = Bundle.main.url(forResource: "elon", withExtension: "jpg")! let uploadResult = Just.post("**http://xxxx.com/uploader.php**", files:["elon": .url(elonPhotoURL, "image/jpeg")]) // <== that's it print(uploadResult.text ?? "")

Not sure if this log info will help?
"iSignature[10575:3106978] bool _WebTryThreadLock(bool), 0x7960e950: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now..."

Clear basic auth credentials

It seems that Just records credentials with ".ForSession" persistence.

Is there a way I can clear these? Ideally, can I make it use "NSURLCredentialsPersistence.None"?

Issue with Xcode Version 6.4 (6E35b

Any recommendations on which version to use? I'm getting the following Carthage error

*** Fetching Just
*** Checking out Just at "v0.1.2"
*** xcodebuild output can be found in /var/folders/vt/kjzw9rb9143d_8yft5r18qmr0000gn/T/carthage-xcodebuild.Oo4D0T.log
*** Building scheme "Just-iOS" in Just.xcodeproj
** BUILD FAILED **


The following build commands failed:
    CpHeader Just-iOS/Just/Just-iOS/Just-iOS.h Build/Products/Release-iphonesimulator/Just.framework/Headers/Just-iOS.h
(1 failure)
error: /Users/Me/Documents/Projects/Login/Carthage/Checkouts/Just/Just-iOS/Just/Just-iOS/Just-iOS.h: No such file or directory
A shell task failed with exit code 65:
** BUILD FAILED **


The following build commands failed:
    CpHeader Just-iOS/Just/Just-iOS/Just-iOS.h Build/Products/Release-iphonesimulator/Just.framework/Headers/Just-iOS.h
(1 failure)```

Possible to POST an array of files?

Hi, I am wondering if it is possible to POST an array of files in a single request? The server expects a field called files[] or just files that is supposed to be an array of files. Is it possible to do this in any way? I can only figure out how to post a single file.

I tried let files: AnyObject = [/* my HTTPFiles */] but that does not work, because array literal can't be used for AnyObject.

The files I am trying to upload is using multipart/form-data.

Thank you.

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.