Alamofire migration problems with ParamerterEncoding - swift

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

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.

Swift 4 using URLSession with non-secure URL

I'm trying to send data to a WebAPI service that uses HTTP and not HTTPS, however I get the following error:
"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
Here is my code:
func logSample(emailSKU:String) -> String {
//let myAPI = "https://itunes.apple.com/us/rss/topmovies/limit=25/json"
let myAPI = "http://<myURlHere>/api/xxx"
let url = URL(string: myAPI)
let session = URLSession.shared.dataTask(with: (url)!) { (data, response, error) in <====== Breaks on this line
print("Response was:")
print(response)
}
session.resume()
return "return something here"
}
The API service works just fine from other applications.
If I use the iTunes url above, then everything works fine, so the only difference is the HTTP ver HTTPS.
I have added 'Allow Arbitrary Loads' declaration to the plist, any ideas?
I checked the RFC 3986 and it is the "|" character that isn't allowed and that you need to encode.
To supplement #Joakims answer:
The URL given is invalid because of the use of the | character and needs to be encoded. You can do this in the following way:
let urlString = "http://example.com/api/Scans?emailSKU=fred#example.com|123456"
if let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
let url = URL(string: encodedURLString)
print(url)
}
Which outputs:
Optional(http://example.com/api/Scans?emailSKU=fred#example.com%7C123456)
So | needs to be encoded, which replaces it with %7C

unexpectedly found nil while unwrapping an Optional value parsing json swift [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 5 years ago.
I try to parse json with swift using following:
let apiPath = "http://samples.openweathermap.org/data/2.5/forecast?q=München,DE&appid=b1b15e88fa797225412429c1c50c122a1"
func getDataWithCompletionHandler(completionHandler: (_ jsonData: JSON?) -> Void) {
let request : URLRequest = URLRequest(url: URL(string: apiPath)!)
Alamofire.request(apiPath, method: .get)
.responseJSON { (response) in
When my app running i got an error on line:
let request : URLRequest = URLRequest(url: URL(string: apiPath)!)
fatal error: unexpectedly found nil while unwrapping an Optional
value.
But i did pass correct string. Why is that error happen?
Your URL string contains special characters so what you need to do is encode your URL string before making URL object from it. There is two way to encode the URL string.
Using addingPercentEncoding(withAllowedCharacters:)
let apiPath = "http://samples.openweathermap.org/data/2.5/forecast?q=München,DE&appid=b1b15e88fa797225412429c1c50c122a1"
if let encodeString = apiPath.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed),
let url = URL(string: encodeString) {
print(url)
}
Using URLComponents
var urlComponent = URLComponents(string: "http://samples.openweathermap.org/data/2.5/forecast")!
let queryItems = [URLQueryItem(name: "q", value: "München,DE"), URLQueryItem(name: "appid", value: "b1b15e88fa797225412429c1c50c122a1")]
urlComponent.queryItems = queryItems
print(urlComponent.url!)
Try this code:
Alamofire.request(“http://samples.openweathermap.org/data/2.5/forecast?q=München,DE&appid=b1b15e88fa797225412429c1c50c122a1”, method: HTTPMethod.get, parameters:nil , encoding: URLEncoding.default, headers: nil).validate().responseJSON { (response) in
if response.result.isSuccess
{
//handle response
}
}
You string content not correct symbol "ü" in this path "q=München".
Replace it to correct symbol "u".

Issue with Alamofire Request

I am trying to use Alamofire to make a web request. It had been working absolutely fine, but after doing a recent pod update it has stopped.
My syntax is:
var params = [String : Any]()
if (data != nil) {
params = try! JSONSerialization.jsonObject(with: data!, options: []) as! [String : Any]
}
let _ = Alamofire.request( "http://example.com" , method: Method, parameters: params?, encoding: .queryString, headers: [:]).response{ (request, response, data, error) in
}
the error looks is "Extra argument 'method' in call" and I don't seem to be able to get rid of it. My parameters of the request to Alamofire.request seem ok to me, but clearly I am missing something.
You're not passing anything to the method parameter. I don't know what you're trying to provide in the encoding parameter either but that went through some changes in Alamofire 4.0. For example and for simplicity's sake, this compiles:
let _ = Alamofire.request( "http://example.com" , method: HTTPMethod.get, parameters: nil, encoding: JSONEncoding.default, headers: nil)

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

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!)