SwiftyJSON upgrading to Swift 2.0 requires to explicitly call .dictionary getter to access values? - swift

In Xcode 6.4 I wrote a simple program in Swif 1.2
by using SwiftyJSON
to parse an HAR i.e: a JSON-formatted archival format for logging HTTP where everything worked great.
Updating to Xcode 7 and Swift 2.0 I also update the SwiftyJSON dependency
, but this broke my program when it tries to access JSON values by a compact syntax like this:
let harVersion = mJSON["log"]["version"].string
In current update this syntax give the following runtime error:
Could not cast value of type 'Swift.String' (0x1002bf218) to 'Swift.Int' (0x100869aa8).
I solved by changing/refactoring the code by adding .dictionary explicitly:
let harVersion = mJSON.dictionary!["log"]!.dictionary!["version"]!.string
I would like to know/understand in details the cause of this behavior and if there is a more elegant/robust/concise way to access JSON values. Any advice is appreciated.
Additional information:
Podfile
platform :osx, '10.11'
use_frameworks!
target 'prova-xcode7-swiftcli' do
pod 'SwiftyJSON', :git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
end
Main.swift:
var request = NSURLRequest(URL: mURL!)
var response: NSURLResponse?
var error: NSError?
var data: NSData? = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response) // , error: &error)
if let httpResponse = response as? NSHTTPURLResponse {
if data != nil {
var mJSON = JSON(data: data!)

Related

Equivalent of Request.serializeResponseJSON - Migration Alamofire 5

I have a problem with the following code:
func request(url: URL, completionHandler: #escaping (AFDataResponse<Any>) -> Void) {
let httpResponse = fakeResponse.response
let data = fakeResponse.data
let error = fakeResponse.error
let result = Request.serializeResponseJSON(options: .allowFragments, response: httpResponse, data: data, error: error)
guard let url = urlBuild(queryType: "q", from: "0", to: "10", uri: nil) else { return }
let urlRequest = URLRequest(url: url)
completionHandler(AFDataResponse(request: urlRequest, response: httpResponse, data: data, result: result))
}
I get the following error with Alamofire 5: Type 'Request' has no member 'serializeResponseJSON'.
I'm new to development with Swift and Alamofire, and I can't find a method equivalent to Request.serializeResponseJSON in Alamofire 5.
Thanks in advance for your help :)
All of the serialize methods from previous versions of Alamofire have been refactored into concrete types. For example, serializeResponseJSON has been replaced by the JSONResponseSerializer, which you can use with the response(responseSerializer:) method. However, for your usage, you shouldn't need to create an instance directly, as you can pass the same parameters to responseJSON. I suggest you use responseDecodable with Decodable types instead of responseJSON, as it will ensure your types are properly parsed.
I also suggest you read through our Usage, Advanced Usage, and API documentation and find some newer tutorials as you start using Alamofire.

Alamofire migration problems with ParamerterEncoding

Having some issues with Alamofire migrating to swift 3. I had this code before working now I'm getting an error. See code below:
let URL = Foundation.URL(string: Router.baseURLString)
let URLRequest = NSMutableURLRequest(url: URL!.appendingPathComponent(path))
let encoding = Alamofire.ParameterEncoding.URL
return encoding.encode(URLRequest, parameters: parameters).0
Getting the error on the 'let encoding =' line.
Error:
Type 'ParameterEncoding' has no member 'URL'
Try this
Alamofire.ParameterEncoding.encode(URLRequest, parameters: parameters).0

I have an error in http get request in swift 2

I have the error:
fatal error: unexpectedly found nil while unwrapping an Optional value
With this Swift Code:
import Alamofire
let request = Alamofire.request(.GET, "http://192.168.2.16/APIPruebas/validalogin/{\"usuario\":\"user\",\"pwd\":\"pwd\",\"id\":\"10\",\"ulogin\":\"1\",\"clogin\":\"1\"}")
print(request)
I think that the problem are the { }
But I donĀ“t know if I escape " correctly with the \ character.
In postman works fine with this request
http://192.168.2.16/APIPruebas/validalogin/{"usuario":"user","pwd":"pwd","id":"10","ulogin":"1","clogin":"1"}
Which is the best metod to do a HTTP GET Request?
Thanks
I think you need to encode the url before using it with api like this
let str = "http://192.168.2.16/APIPruebas/validalogin/{\"usuario\":\"user\",\"pwd\":\"pwd\",\"id\":\"10\",\"ulogin\":\"1\",\"clogin\":\"1\"}"
let encodedUrl = str.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())
Now pass encodedUrl in Alamofire.request method.

countForFetchRequest in Swift 2.0

I am trying to use the countForFetchRequest method on a managed object context in Swift 2.0.
I note that the error handling for executeFetchRequest has been changed across to the new do-try-catch syntax:
func executeFetchRequest(_ request: NSFetchRequest) throws -> [AnyObject]
but the countForFetchRequest method still uses the legacy error pointer:
func countForFetchRequest(_ request: NSFetchRequest,
error error: NSErrorPointer) -> Int
...and I am having a bit of trouble figuring out how to use this in Swift 2.0.
If I do the same thing as pre-Swift 2.0:
let error: NSError? = nil
let count = managedObjectContext.countForFetchRequest(fetchRequest, error: &error)
I get errors saying to remove the &, but if I remove that I get another error saying that NSError cannot be converted to an NSErrorPointer.
Any help would be appreciated about how to get this working.
Your code is almost correct, but error needs to be a variable, in order to be passed as
inout-argument with &:
var error: NSError? = nil
let count = managedObjectContext.countForFetchRequest(fetchRequest, error: &error)
Update: As of Swift 3, countForFetchRequest
throws an error:
do {
let count = try managedObjectContext.context.count(for:fetchRequest)
return count
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
return 0
}
You need to do like this:
let error = NSErrorPointer()
let fetchResults = coreDataStack.context.countForFetchRequest(fetchRequest, error: error)
print("Count \(fetchResults)")
This is the code for Swift 2.0

Error : Command failed due to signal : Segmentation fault: 11

I am trying to get an array from dictionary, but I am getting an error for below line
self.items = self.dataDictionary["geoNames"] as NSArray
Complete code is as below
var dataDictionary: AnyObject!
var items: NSArray!
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(string: "http://api.geonames.org/countryInfoJSON?username=temp")
var urlRequest = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(urlRequest, queue:NSOperationQueue(), completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if (data.length > 0 && error == nil){
self.dataDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)
println(self.dataDictionary)
self.items = self.dataDictionary["geoNames"] as NSArray
}
})
}
A Hypothesis: If the editor is - for some reason - unable to parse through your code and make conclusions about the correctness of your code, it might allow you to compile even if you have syntax errors, which might lead to the error you describe.
I was getting this error because of syntax errors. Namely, I was changing a 1D array to a 2D array, but had forgotten to update some of the places it is initialized.
It seems that the editor was unable to pinpoint exactly where the errors were and when I tried compiling, I got the error you are describing. I suspected something funky was going on with the editor because it was flashing between all-white and colored syntax, and throwing the "An internal error happened" error message at the top of the editor.
So if you have this error, manually double-checking your code or undoing your changes one by one until you get to a stage where you can compile successfully might give you a hint of what's going wrong.
Posting because it might be helpful to someone facing a similar issue.
I had the same error with a cocoapod install and noticed my Foundation.framework stop being recognized. Take a look at my answer here on this thread which solved my problem. Hope this helps someone.
In the event you don't want to visit the link, simply run
sudo gem install cocoapods
to update the pods if you suspect your outdated cocoa pods are giving you trouble with the frameworks
There are a few problems with your code:
Your code does not even compile. Segfault is coming from the compiler, not at runtime
You should cast the result from JSONObjectWithData as
NSDictionary, not assign to a variable of type AnyObject!
Should use if to check if the casting works
The dictionary key is wrong. It is geonames (all lowercase)
Here is the functional code:
var url = NSURL(string: "http://api.geonames.org/countryInfoJSON?username=temp")
var urlRequest = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(urlRequest, queue:NSOperationQueue(), completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if (data.length > 0 && error == nil){
if let jsonObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary {
let dataDictionary = jsonObject["geonames"]
println(dataDictionary)
}
}
})
This happened to me because I incorectly created an if statement. Very very simple error, I just missed one key, but caused a world a difference.:
if textBox?.characters.count = 0{
//...
}
instead I needed to do:
if textBox?.characters.count == 0{
//...
}