daltoniam / swifthttp Goto Github PK
View Code? Open in Web Editor NEWThin wrapper around NSURLSession in swift. Simplifies HTTP requests.
License: Apache License 2.0
Thin wrapper around NSURLSession in swift. Simplifies HTTP requests.
License: Apache License 2.0
It would be nice to be able to include this library via CocoaPods!
Hi I want to use swifthttp to get a array of returned json objects... Is this possible? I can't find a way to achieve this.. Here is what I got..
func requestAllCars() {
var request = HTTPTask()
let params: Dictionary<String, String> = ["apikey":apikey, "username":username]
request.requestSerializer = JSONRequestSerializer()
request.responseSerializer = JSONResponseSerializer()
request.POST(url, parameters: params, success: {(response: HTTPResponse) in
if let dict = response.responseObject as? Dictionary<String, String> {
println("print the whole response: \(dict)")
if let statusCode: AnyObject = dict["status"] {
if statusCode as NSString == "Error" {
// Oops error
})
}
} else {
}
}
}, failure: {(error: NSError, response: HTTPResponse?) in
println("object not received \(error)")
})
})
}
Might be because I am not 10.10
Any plans for adding headers to the request and also reading headers from the response?
SwiftHTTP is perfect.
But when i tried to use OpenUDID ( https://github.com/ylechelle/OpenUDID ) , Xcode reported a wrong.
#import <CommonCrypto/CommonCrypto.h>
#import "OpenUDID.h"
I'm trying to HTTP POST (using Swift) to my server and I'm getting this error:
2015-01-04 20:09:43.196 PIPiOS[1308:47829] CFNetwork SSLHandshake failed (-9805) 2015-01-04 20:09:43.197 PIPiOS[1308:47829] NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9805)
Any idea what's going on? POST works fine otherwise (using Java or PHP)
Target: iOS8.1
I have two button in test app, one is check the status of login and the second is login
1、I click the login button
2、The login status is true When I click the check button
3、Close the application and open again
4、The login status is false When I click the check button
We use sessionid in cookies to check login status in server
Hi.
I'm trying to reproduce my Go code https://github.com/msamoylov/insuranceutil/blob/master/main.go in Swift and it doesn't seem to work. I keep getting an error message saying that 'personal code' field wasn't sent.
My implementation is https://gist.github.com/msamoylov/5152ed92456fd557b540
Any ideas? Thanks.
Just pulled this down to test it out. Looks great.
Pinged a local REST api and get the following
{{""ssuucccceesss"s:"t:rtureu,e",i"di"d:"":8"78a78ab8466604-04-f41f71-71-11e14e-49-891881-8a-1a917937f3bfab8af8ef3e"3,"",a"caccocuonutnst"s:"[:][}]
This is true with anything - errors, responses, etc. Repeats letters multiple times.
I'm trying to archive my app to submit to ITC for review. When I try and Archive, I get an error Could not build Objective-C module 'SwiftHTTP'
I've cleared out my DerivedData and everything I can think of. Is there something wrong with this framework or am I just missing a step?
I get the following error when I try and build a fresh project in XCode 6.1.1 after adding this library via CocoaPods.
Anybody experienced this before and know what the deal is?
Cheers
var request = HTTPTask()
request.requestSerializer = JSONRequestSerializer()
request.responseSerializer = JSONResponseSerializer()
request.POST("http://" + self.host + "/authentication",parameters: ["email": self.username, "password": self.password], success: {
(response: HTTPResponse) -> Void in
if response.responseObject {
let dict = response.responseObject as Dictionary<String, AnyObject>
println(dict)
}
},
failure: {(error: NSError) -> Void in
println(error)
})
Produces this error & Xcode's proposed fix:
Xcode's fix compiles and works in simulator.
I have a problem, when I call request.GET but returned result after collectionView.reloadData
let result = Array()
let api: Api = Api()
self.result = api.getData()
self.collectionView.reloadData()
I thinks it can be solve by sync. please help me
Do you know how to get this to work in the playground?
Hi,
If you could add support for basic http authentication.
Thanks !
Pursuant to http://stackoverflow.com/q/27949677/1271826, the didReceiveChallenge
should probably only try a particular set of credentials once. If they were wrong, the existing implementation would try repeatedly.
Therefore, I might suggest changing:
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
if let a = auth {
let cred = a(challenge)
if let c = cred {
completionHandler(.UseCredential, c)
return
}
completionHandler(.RejectProtectionSpace, nil)
return
}
completionHandler(.PerformDefaultHandling, nil)
}
To:
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
if let credential = auth?(challenge) {
if challenge.previousFailureCount == 0 {
completionHandler(.UseCredential, credential)
} else {
completionHandler(.RejectProtectionSpace, nil)
}
} else {
completionHandler(.PerformDefaultHandling, nil)
}
}
This will only try using the credentials provided once.
Im having issue with my test app.. my IBAction
@IBAction func whenSigninIsTapped(sender : AnyObject) {
var request = HTTPTask()
request.requestSerializer = JSONRequestSerializer()
request.responseSerializer = JSONResponseSerializer()
request.POST("http://localhost:3000/api/v1/login", parameters:["email":"[email protected]","password":"password"],
success: {(response: AnyObject?) -> Void in
let resp = response as Dictionary<String,AnyObject>
},failure: {(error: NSError) -> Void in
})
}
But it is causing a build failed with error Cannot convert the expression's type '()' to type 'Dictionary<String, String> specifically the line below
extraResponse.headers = hresponse.allHeaderFields as Dictionary<String,String>
It looks like a casting issue as allHeadersFields is a NSDictionary?
Hi there
I'm new to Xcode and iOS so please bear with me. I don't seem to be able to import this into my iOS project.
I have followed these steps in Xcode 6.1:
The framework files are red.
When I compile I receive an "Apple Mach-O Linker Error":
Undefined symbols for architecture x86_64:
"__TFC9SwiftHttp8HTTPTaskCfMS0_FT_S0_", referenced from:
__TFC12HileniumAuth14ViewController11viewDidLoadfS0_FT_T_ in ViewController.o
"__TMaC9SwiftHttp8HTTPTask", referenced from:
__TFC12HileniumAuth14ViewController11viewDidLoadfS0_FT_T_ 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)
Any help would be much appreciated.
Cheers
Matt
Hi, Im new in this, I'm wotking with Swift HTTP and JSONJoy
Everything is OK and compile and upload to simulator, but when I call webservice I have an error on JSONJoy.framework, it says no image found
Please can you help me
I was tinkering with the library and I wanted to share, off the top of my head, my own implementation of multiple file downloads using multiple downloadTasks
with the same background Session. Not sure if this is kosher though.
public func downloadMultiple(urls: Array<String>, parameters: Dictionary<String,AnyObject>?,progress:((Double) -> Void)!, success:((HTTPResponse) -> Void)!, failure:((NSError, HTTPResponse?) -> Void)!) -> [String:NSURLSessionDownloadTask?] {
var tasks = Dictionary<String,NSURLSessionDownloadTask>()
let ident = createBackgroundIdent()
let config = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(ident)
let session = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
for url in urls {
let serialReq = createRequest(url,method: .GET, parameters: parameters)
if serialReq.error != nil {
failure(serialReq.error!, nil)
tasks[url] = nil
}
let task = session.downloadTaskWithRequest(serialReq.request)
let taskId = ident + "-" + String(task.taskIdentifier)
self.backgroundTaskMap[taskId] = BackgroundBlocks(success,failure,progress)
task.resume()
tasks[url] = task
}
return tasks
}
Let me know what you think. I can put that into a pull request.
I have a problem with the NSOperationQueue
example. There are only maxConcurrentOperationCount
requests and all other requests will not called.
If I try this example, only Request one is called but not Request two. If I set maxConcurrentOperationCount
to 2
, both requests are called.
let operationQueue = NSOperationQueue()
operationQueue.maxConcurrentOperationCount = 1
var request = HTTPTask()
var opt = request.create("http://vluxe.io", method: .GET, parameters: nil, success: {(response: HTTPResponse) in
println("Request one")
},failure: {(error: NSError, response: HTTPResponse?) in
println("error: \(error)")
})
if let o = opt {
operationQueue.addOperation(o)
}
opt = request.create("http://vluxe.io", method: .GET, parameters: nil, success: {(response: HTTPResponse) in
println("Request two")
},failure: {(error: NSError, response: HTTPResponse?) in
println("error: \(error)")
})
if let o = opt {
operationQueue.addOperation(o)
}
Is it possible/what is the best way to POST multiple files?
Hello,
I am using SwiftHTTP to create an app for managing drupal 8 websites, the get requests work fine as they are accessable without authentication.
However, when I want to post new content to the site I'm getting an 403 error.
I can't find it in the code anywhere where the HTTPAuth class is even used to send the authentication credentials in a header (or whatever) to the server.
I just need a basic http authentication for this to work, but I guess it's not implemented? Or I am really blind. :p
Okay, so I found the implementation to URLSession, but I wounder why it's not working for me.
Added some println's to HTTPTask that don't get executed.
line 419 to check if it's calling the function and 423 to confirm.
Nothing prints
The delegate function URLSession for authentication never gets fired.
I'm using POST to login and get a token that is in URL fragment (hash) after a bunch of redirects. How can I get final URL back from response object?
Hello,
i have tried today to run my project on the new xcode 6.3 beta with swift 1.2, but i have seen that your project isn´t compatible with this swift version. For example i have to replace: var opt = self.create(url, method:.DELETE, parameters: parameters,success,failure) with var opt = self.create(url, method: .GET, parameters: parameters, success: success, failure: failure).
Hey @ all,
i have found an Issue, when you want to download an image from Webserver, and copy it from temp directory to documents directory:
This is the line, that have to replace:
let newPath = NSURL(string: "(paths[0])/(response.suggestedFilename!)")!
with:
NSURL(fileURLWithPath: "(path)/(fileName)")
because:
You want to move pathURL but newPath is not a FILEPATH (file://....)
So here is my code:
if response.responseObject != nil {
let filePath = response.responseObject as? NSURL
if let url = filePath {
if let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String {
if let fileName = response.suggestedFilename {
if let newPath = NSURL(fileURLWithPath: "\(path)/\(fileName)") {
let fileManager = NSFileManager.defaultManager()
fileManager.removeItemAtURL(newPath, error: nil)
fileManager.moveItemAtURL(url, toURL: newPath, error:nil)
}
}
}
}
}
Hi,
I'm getting an error when i'm trying to upload a file using file path.
This is the code i'm running:
let fileUrl = NSURL.fileURLWithPath("/Users/Marco/Documents/test.m4a")
var request = HTTPTask()
request.POST("http://www.example.com", parameters: ["p1": "v1", "p2": "v2", "file": HTTPUpload(fileUrl: fileUrl!)], success: {(response: HTTPResponse) -> Void in
if response.responseObject != nil {
let data = response.responseObject as NSData
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
println("response: \(str)")
}
},failure: {(error: NSError) -> Void in
println(error)
})
Then, from the 'HTTPRequestSerializer' class, from the 'dataFromParameters' function, I get an error in the following line:
mutData.appendData(upload.data!)
which prints: fatal error: unexpectedly found nil while unwrapping an Optional value
I suppose this is happening because the function is expecting a data blob file, which has a different constructor in HTTPUpload class.
convenience init(data: NSData, fileName: String, mimeType: String) {
self.init()
self.data = data
self.fileName = fileName
self.mimeType = mimeType
}
Just followed the installation instructions, opened myprojectname.xcworkspace, imported SwiftHTTP in one of the classes, got these errors. Sorry I'm fairly new to iOS, swift and cocoapods. Thank you 😄
Here is a screenshot of all the errors:
https://www.dropbox.com/s/5k0zu7l50jdxt45/Screenshot%202015-02-03%2021.56.56.png?dl=0
Is it possible that I can POST files(such as images)?
Hi. Good chance i'm missing something, but the given examples such as:
var request = HTTPTask()
request.baseURL = "http://api.someserver.com/1"
request.GET...
Don't work because each http method in the Task class, such as get, create a new HTTP task instead of using self.
func GET(url: Str... {
var task = HTTPTask()
task.run(url,method: .GET,parameters: parameters,success,failure)
}
So any property set in the first snippet, whether it be baseURL or a custom request serializer, don't get used. Am i missing something or should the second snippet NOT create a new Task() and instead use self?
Thanks!
My JSON response has a key holding an array, is it possible that I can access its array elements only using SwiftHTTP?
SyntaxError - /Users/<mycomp>/Desktop/iPhone Dev/<projectFolder>/Podfile:6: syntax error, unexpected tCONSTANT, expecting end-of-input
pod 'SwiftHTTP', :git => "https://github.co...
^
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:254:in `eval'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:254:in `block in from_ruby'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:51:in `instance_eval'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:51:in `initialize'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:251:in `new'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:251:in `from_ruby'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-core-0.36.0/lib/cocoapods-core/podfile.rb:227:in `from_file'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.0/lib/cocoapods/config.rb:176:in `podfile'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.0/lib/cocoapods/command.rb:109:in `verify_podfile_exists!'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.0/lib/cocoapods/command/project.rb:100:in `run'
/Library/Ruby/Gems/2.0.0/gems/claide-0.8.1/lib/claide/command.rb:312:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.0/lib/cocoapods/command.rb:46:in `run'
/Library/Ruby/Gems/2.0.0/gems/cocoapods-0.36.0/bin/pod:44:in `<top (required)>'
/usr/bin/pod:23:in `load'
/usr/bin/pod:23:in `<main>'
[!] Oh no, an error occurred.
It appears to have originated from your Podfile at line 6.
Even though an HTTP status code may denote an error, APIs can still return valuable information in the body of the response (human readable messages for example). Currently there is no way to get access to the response in the failure handlers (as far as i can tell) even though when these error status codes are received the response is still created and its body parsed.
I'm trying to convert the response to a dictionary (as specified in Readme example) but I'm getting this error while doing that.
Cannot convert the expression's type 'Dictionary<$T1,$T2>' to type 'Hashable'
var request = HTTPTask()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
request.responseSerializer = JSONResponseSerializer()
}
@IBAction func fetchPollClicked(sender:UIButton) {
request.GET("http://www.abc.com/api", parameters: nil, success: {(response: AnyObject?) -> Void in
if response {
let resp = response as Dictionary // Error in on this line
println("response \(resp))")
}
}, failure: {(error: NSError) -> Void in
println("error \(error)")
})
}
Api returns a deep nested JSON. What could be the issue?
From the SwiftHTTP documentation:
"Add the SwiftHTTP.xcodeproj to your Xcode project. Once that is complete, in your "Build Phases" add the SwiftHTTP.framework to your "Link Binary with Libraries" phase."
I only see the SwiftHTTPOSX.framework in the add framework dialog box, but not the SwiftHTTP.framework. The thing is I am developing an app for iOS...
I guess I may have done something wrong? What is the correct way to add the SwiftHTTP.xcodeproj to my iOS xCode project? Sorry I am new to this...
I'm having this error after add your framework:
SwiftHTTP-master/Tests/SwiftHTTPTests.swift:9:8: Cannot load underlying module for 'XCTest' SwiftHTTP-master/README.md' of type net.daringfireball.markdown for architecture i386
I'm trying to do a login and get the cookies from server.
func foo(username: String, password: String) -> Bool {
var url = "http://example"
var request = HTTPTask()
var parameters = ["username": username, "password": password]
var result = false;
request.requestSerializer = JSONRequestSerializer()
request.POST(url, parameters: parameters,
success: {
(response: HTTPResponse) in
if response.responseObject != nil {
result = true
},
}, failure: {(error: NSError) in
println(" error \(error)")
})
return result;
}
Since its running async, my result
always is false. Any suggestion of fixing it? Thanks.
Please, implement the file upload as soon as possible ! I (we) need it in this awesome library ! :D
Can you please help a noob?
I would like to use swift to do what is described in this python script:
#coding: utf-8
# These code snippets use an open-source library. http://unirest.io/python
import requests
req = requests.request("POST","https://textanalysis.p.mashape.com/segmenter",
headers={
"X-Mashape-Key": "jhzbBPIPLImsh26lfMU4Inpx7kUPp1lzNbijsncZYowlZdAfAD",
"Content-Type": "application/json"
},
params={
"text":"这是中文测试"
}
)
print req
print req.json()
Can you make an example using SwiftHTTP?
Awesome job with the wrapper 👍
Just wondering if there would be any attempt in the future to support retried downloads for the download
call like this
request.download(url: String,
retries: Int /* number of retries */
parameters: Dictionary<String,AnyObject>?,
progress:((Double) -> Void)!,
success:((HTTPResponse) -> Void)!,
failure:((NSError, HTTPResponse?) -> Void)!)
It's useful to retry from the original call rather than calling the request.download
from within the failure closure
. May be there's a better way to do it :)
var UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileUrl?.pathExtension , nil);
Error : NSString is not a subtype of 'CFString'
FIle : HTTPUpload.swift
It works great on the simulator, but it crashes once I deployed to the real machine.
Environment: Maverick 10.9.5, Xcode 6.1, iOS 8.1
dyld: Library not loaded: @rpath/JSONJoy.framework/
I understand it quite different from compiling on the simulator (linking against the frameworks) verse on the real machine. Could you help me on this?
Thanks @daltoniam
Hi
I was using SwiftHTTP to create a Mac app for the website. I have my own REST API. Using the basic Auth, I have to send the request to some url to get the apikey.
import SwiftHTTP
var request = HTTPTask()
request.GET("https:[email protected]:[email protected]/api/v3/auth/token", parameters: nil, success: {(response: HTTPResponse) in
//code
}, failure: {(error: NSError, response: HTTPResponse?) in
//error
})
The url has to be sent in that format to get the apikey from the api. The GET request for normal domain like "http://github.com" was working. But for this kind of url's, I was getting an error like
error: Error Domain=HTTPTask Code=401 "accessed denied" UserInfo=0x600000234d80 {NSLocalizedDescription=accessed denied}
.
Please help to overcome with this.
Could you please have a look at my stackoverflow question?: http://stackoverflow.com/questions/27723917/how-can-i-return-the-json-property-of-this-swifthttp-function-as-a-string
is support ios 7?thank you!
thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.