Using API in Swift (Postman,Alamofire,SwiftyJson) - ios

I have an admin panel which admin can insert question and gives 3 options of answers to users to choose. The admin is able to insert questions according to different chapters...its like a quiz game..The correct answer is then given an int value so in my collection of 3 buttons, I am able to know which is the correct button user has chosen. But now my problem is, in my Postman:
in my swift code
func getaQuestionaByaChapter(chapterName: String,question: String, answer1: String, answer2 : String, answer3: String, answer: Int, completion: #escaping (JSON?, Error?) -> Void) {
let parameters: [String : Any] = [
"secret_key" : "b3370e1590a2cf2b430e8cf8a8b361bd",
"_action" : "GETQUESTIONBYCHAPTER",
"GETQUESTIONBYCHAPTER" : chapterName,
"question" : question,
"option1" : answer1,
"option2" : answer2,
"option3" : answer3,
"answer" : answer
]
is this a declaration correct?
as for my storyboard:
and after this, i would be doing
button1.setTitle = answer1
questionlabel.text = question
in my swift file for the part where i link my API
import SwiftyJSON
import Alamofire
public class EduappRestClient {
enum ContentType: String {
case json = "application/json"
case jpeg = "image/jpeg"
case formEncoded = "application/x-www-form-urlencoded"
case none = "" //Content type will be empty
}
private static let url: URL = URL(string: "http://192.168.0.127:81/project/Online_Question/API/actiona")! //NSURL depreciated now using URL)
//singleton
static let sharedClient: EduappRestClient = EduappRestClient()
class func request(with url: URL,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
contentType: ContentType = .json,
encoding: ParameterEncoding = JSONEncoding.default,
additionalHeaders: [String: String] = [:],
completion: #escaping(JSON?, Error?) -> Void
) {
//MARK: Configure Headers
var headers: [String: String] = [:]
//if contenttype is specified as none type, leave content-type header field empty
if contentType != .none {
headers["Content-Type"] = contentType.rawValue
}
for (key, value) in additionalHeaders {
headers[key] = value
}
Alamofire.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers).responseJSON(completionHandler: { (response) in
guard response.result.error == nil, let value = response.result.value else {
completion(nil, response.result.error)
return
}
let jsonData = JSON(value)
completion(jsonData, nil)
})
}
//MARK: - Getting questions by chapters
func getaQuestionaByaChapter(chapterName: String,question: String, answer1: String, answer2 : String, answer3: String, answer: Int, completion: #escaping (JSON?, Error?) -> Void) {
let parameters: [String : Any] = [
"secret_key" : "b3370e1590a2cf2b430e8cf8a8b361bd",
"_action" : "GETQUESTIONBYCHAPTER",
"GETQUESTIONBYCHAPTER" : chapterName,
"question" : question,
"option1" : answer1,
"option2" : answer2,
"option3" : answer3,
"answer" : answer
]
let URLString = EduappRestClient.url
EduappRestClient.request(with: URLString, method: .post, parameters: parameters) { (json, error) in
guard error == nil, let json = json else {
completion(nil, error)
return
}
let result: JSON = json[1]
//result will print
//"question": [
// {
//"question": "10+10",
//"chapter_name": "Chapter 2",
//"option1": "10",
//"option2": "20",
//"option3": "30",
//"answer": "20"
//}
//]
completion(result, nil)
}
}}
it will show my data accordingly??

After API response, you have to use.
class QuestionModel: Codable {
let questions: [Details]
}
class Details: Codable {
let question: String?
let chapter_name: String?
let option1: Int?
let option2: Int?
let option3: Int?
}
And after this, you have to parse the response in the model data:
func getaQuestionaByaChapter(chapterName: String, completion: #escaping (QuestionModel?, Error?) -> Void) {
let parameters: [String : Any] = [
"secret_key" : "b3370e1590a2cf2b430e8cf8a8b361bd",
"_action" : "GETQUESTIONBYCHAPTER",
"GETQUESTIONBYCHAPTER" : chapterName
]
let URLString = EduappRestClient.url
EduappRestClient.request(with: URLString, method: .post, parameters: parameters) { (json, error) in
guard error == nil, let json = json else {
completion(nil, error)
return
}
do {
let jsonData = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
let result = try JSONDecoder().decode(QuestionModel.self, from: jsonData)
completion(result, nil)
} catch let message {
print("JSON serialization error:" + "\(message)")
}
}
}}
Then in QuizViewController: You have to set the data:
EduappRestClient.sharedClient.getaQuestionaByaChapter(chapterName: "Chapter 2", completion: { (response, error) in
//json is the result from rest client
let firstQuestion = response?.questions.first
self.questionsLabel.text = firstQuestion?.question
self.answerButtons.setTitle("\(firstQuestion?.option1)", for: UIControlState.normal)
self.answerButtons.setTitle("\(firstQuestion?.option2)", for: UIControlState.normal)
self.answerButtons.setTitle("\(firstQuestion?.option3)", for: UIControlState.normal)
})

Related

Converting Graph API from Swift 3 to Swift 5 for Facebook SDK

I am developing an app that allows the user to login using Facebook. The code snippet I have is using Swift 3 though and I can't find a converter online. The Swift 3 code is as follows:
In the example which is in Swift 3, Xcode suggests:
request.start(completion: ((HTTPURLResponse?, GraphRequestResult<GraphRequest>) -> Void)?)
And the programmer then enters (this is the entire function):
func getUserInfo(completion: #escaping (_ : [String: Any]?, _ : Error?) -> Void) {
let request = GraphRequest(graphPath: "me", parameters: ["fields" : "id,email,picture"])
request.start { response, result in
switch result {
case .failed(let error):
completion(nil, error)
case .success (let graphResponse):
completion(graphResponse.dictionaryValue, nil)
}
}
When I start to type:
request.start
Which gives me this line of code:
request.start(completionHandler: GraphRequestBlock?)
How can I convert this from Swift 3 to Swift 5?
Update after comment
My "HomeAfterLogInViewController.swift" file is as follows:
import Foundation
import FacebookCore
import FacebookLogin
class HomeAfterLogInViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
getFacebookProfileInfo()
}
}
func getFacebookProfileInfo()
{
let requestMe = GraphRequest.init(graphPath: "me", parameters: ["fields" : "id,name,email,picture.type(large)"])
let connection = GraphRequestConnection()
connection.add(requestMe, completionHandler:{ (connectn, userresult, error) in
if let dictData: [String : Any] = userresult as? [String : Any]
{
DispatchQueue.main.async
{
if let pictureData: [String : Any] = dictData["picture"] as? [String : Any]
{
if let data : [String: Any] = pictureData["data"] as? [String: Any]
{
print(data)
print(dictData["email"]!)
}
}
}
}
})
connection.start()
}
And this code works but there is one more step I need - explained in the screenshot:
func getFacebookProfileInfo() {
let requestMe = GraphRequest.init(graphPath: "me", parameters: ["fields" : "id,name,email,picture.type(large)"])
let connection = GraphRequestConnection()
connection.add(requestMe, completionHandler: { (connectn, userresult, error) in
if let dictData: [String : Any] = userresult as? [String : Any] {
DispatchQueue.main.async {
if let pictureData: [String : Any] = dictData["picture"] as? [String : Any] {
if let data : [String: Any] = pictureData["data"] as? [String: Any] {
print(data)
print(dictData["email"]!)
}
}
}
}
})
connection.start()
}
Try the below code to get the information of the user.
let params = ["fields":"email, id, name, first_name, last_name,gender"]//, user_gender, user_birthday"]
let request = GraphRequest(graphPath: "me", parameters: params, accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion)
request.start { (response, result) in
switch result {
case .success(let value):
print(value.dictionaryValue!)
var parsedData = value.dictionaryValue as Dictionary<String, AnyObject>?
if let firstName = parsedData?["first_name"] {
print("First Name: \(firstName)")
}
if let lastName = parsedData?["last_name"] {
print("Last Name: \(lastName)")
}
if let email = parsedData?["email"] {
print("Email: \(email as! String)")
}
if let id = parsedData?["id"] {
let faceBookId = id as! String
print("Facebook Id: \(faceBookId)")
//you can get profile picture URL here.
let pictureURL = "https://graph.facebook.com/" + "\(faceBookId)/" + "picture?type=large&return_ssl_resources=1"
print("Profile Picture URL: \(pictureURL)")
}
case .failed(let error):
print(error.localizedDescription)
}
}
GraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
if error == nil{
//everything works print the user data
if let userInfo = result as? [String: Any] {
if let email = userInfo["email"] as? String {
let firstName = userInfo["first_name"] as? String
let lastName = userInfo["last_name"] as? String
var profilePicUrl: String? = nil
if let fbUserId = userInfo["id"] as? String {
profilePicUrl = "http://graph.facebook.com/\(fbUserId)/picture?type=large"
}
//Do your operations here.
}
}
}
})
Hope that will help!

Comparing non-optional value of type 'JSON' to 'nil' always returns true. Any suggestion to fix this?

if let vendorId = vendor?.id {
APIManager.shared.getProducts(vendorId: vendorId, completionHandler: { (json) in
if json != nil { <<<<<<<<<Comparing non-optional value of type 'JSON' to 'nil' always returns true
self.products = []
if let tempProducts = json["products"].array {
for item in tempProducts {
let product = Product(json: item)
self.products.append(product)
}
self.tableView.reloadData()
Helpers.hideActivityIndicator(self.activityIndicator)
}
}
})
}
}
In My APIManager.swift
import Foundation
import Alamofire
import SwiftyJSON
import FBSDKLoginKit
class APIManager {
static let shared = APIManager()
let baseURL = NSURL(string: BASE_URL)
var accessToken = ""
var refreshToken = ""
var expired = Date()
// Request Server Function
func requestServer(method: Alamofire.HTTPMethod , path: String, params: [String: AnyObject]?, encoding: ParameterEncoding, completionHandler: #escaping (JSON?) -> Void ) {
let url = baseURL?.appendingPathComponent(path)
refreshTokenIfNeed {
AF.request(url!, method: method, parameters: params, encoding: encoding, headers: nil).responseJSON{ response in
switch response.result {
case .success(let value):
let jsonData = JSON(value)
completionHandler(jsonData)
break
case .failure:
completionHandler(nil)
break
}
}
}
}
// API - Getting the latest order (Customer)
func getLatestOrder(completionHandler: #escaping (JSON) -> Void) {
let path = "api/customer/order/latest/"
let params: [String: Any] = [
"access_token": self.accessToken
]
requestServer(method: .get, path: path, params: params as [String : AnyObject], encoding: URLEncoding()) { (json) in
print(json!)
}
}
}
as json is non optional in your case, comparing it with nil will always return true.
You simply cannot compare it with nil.
If you expect it to be nil, then it should be optional.
If you are sure that it will never be nil, let it be like it is now, just remove the if condition. But be aware that if it goes nil during runtime it would cause crash.

Web service is called twice

I have a problem with a webService call.
The problem is that when I call the service, and debug code, and print log in console, I'm sure my webService is only called once (log print once in console), but my request is apparently sent twice to the server and I have duplicate data in the list.
I know that it's not a server-side problem because it only happens on IOS (not Android).
Here is my code for call services:
public class PersistencyManager {
public func SendPostHttpRequest(baseURL: String, parameter: [String:Any], content: String, closure:#escaping ((_ success:JSON,_ error:NSError?) -> Void)) {
let manager = Alamofire.SessionManager.default
debugPrint("Request parameter ------>",parameter)
debugPrint(" Service URL -------> \(baseURL)")
if let url = URL(string: baseURL) {
var urlRequest = URLRequest(url: url)
urlRequest.setValue("text/html; charset=utf-8", forHTTPHeaderField: "Content-Type")
urlRequest.setURLEncodedFormData(parameters: parameter)
manager.request(urlRequest).responseJSON { response in
switch response.result {
case .success(let JSON) :
debugPrint("get Json response ---> \((JSON)) ")
closure(JSON,nil)
case .failure(let error):
closure(nil,error as NSError)
debugPrint("get error ---> \((error.localizedDescription)) ")
}
}
}
}
}
class LibraryAPI {
static let shareInstance : LibraryAPI = { LibraryAPI() }()
private let persistencyManager : PersistencyManager
init() {
persistencyManager = PersistencyManager()
}
func GetPostResponse(baseURL : String,parameters:[String:Any],contentType: String,closure:#escaping ((_ success:PersistencyManager.JSON,_ error:NSError?) -> Void)) {
persistencyManager.SendPostHttpRequest(baseURL: baseURL, parameter: parameters, content: contentType, closure: { success, error in
closure(success, error)
})
}
}
class TransactionAPI: TransactionProtocol {
static let shareInstance: TransactionAPI = {TransactionAPI()}()
func AddNewManagerRequest(_ parameter: [String : Any], closure: #escaping (([String : Any]?, NSError?) -> Void)) {
let url = Constants.BaseURL + Constants.K_NEWREQPORTERAGE
LibraryAPI.shareInstance.GetPostResponse(baseURL: url, parameters: parameter, contentType: "JSON", closure: {success,error in
var response: [String:Any]?
if let json = success as? [String: Any] {
response = json
}
closure(response, error)
})
}
}
class AddNewOrderViewController: MainViewController {
private func RegisterForNewPorterageRequest() {
let time = Utilities.shareInstance.GetSystemTime()
guard let userID = UserDefaults.standard.value(forKey: "user_id") as? String else {
return
}
StartActivity(activityColor: Constants.ACTIVITY_COLOR)
let token = TokenCreator.shareInstance.CreateTokenWithUserID(userID: userID, methodName: Constants.M_NEWREQUESTPORTERAGE)
request.tok = token
request.time = time
request.user_id = userID
let jsonModel = Utilities.shareInstance.GetJsonForm(objectClass: request)
TransactionAPI.shareInstance.AddNewManagerRequest(jsonModel, closure: {[weak self] success,error in
guard let strongSelf = self else{
return
}
if error != nil {
OperationQueue.main.addOperation {
strongSelf.StopActivity()
strongSelf.CreateCustomTopField(text: Constants.serverError, color: Constants.ERROR_COLOR)
}
}
else {
if let response = success {
debugPrint("add request service call once")
if let status = response["status"] as? String {
if status == "succ" {
OperationQueue.main.addOperation {
strongSelf.presentResultAlert()
}
}else {
OperationQueue.main.addOperation {
strongSelf.StopActivity()
strongSelf.CreateCustomTopField(text: Constants.send_data_error, color: Constants.ERROR_COLOR)
}
}
}
}
}
})
}
}
After adding log to server, I made sure my request was sent twice to server.
All console log print once in console.
I don't know when I call service twice, and why my request was sent twice to the server.
I don't understand how the log be displayed once, but the service has been called twice?
Any help appreciated.
It's really confusing, but it works perfectly with this method.
i have this method in persistencyMangerClass and i using this method instead SendPostHttpRequest.What really is the difference between these two methods. :|
public func SendMultiPartRequestWith(baseUrl: String, parameters: [String : Any],closure: #escaping ((_ success:JSON,_ error:NSError? ) -> Void)){
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 30
manager.session.configuration.timeoutIntervalForResource = 15
debugPrint(" Service URL -------> \(baseUrl)")
debugPrint("Request parameter ------>",parameters)
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data"
]
manager.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
if let data = value as? Data {
let fileName = (key as String) + ".jpg"
let mimType = (key as String) + "/jpg"
multipartFormData.append(data, withName: key as String, fileName: fileName, mimeType: mimType)
}
else {
if let v = value as? String {
multipartFormData.append("\(v)".data(using: String.Encoding.utf8)!, withName: key as String)
}else {
multipartFormData.append("".data(using: String.Encoding.utf8)!, withName: key as String)
}
}
}
}, usingThreshold: UInt64.init(), to: baseUrl, method: .post, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseString { response in
if let err = response.error{
closure(nil, err as NSError)
return
}
if let JSON = response.result.value {
closure(JSON, nil)
}
}
case .failure(let error):
closure(nil, error as NSError)
}
}
}

POST Json to API with Alamofire?

I want to post a JSON object I create in my service class and pass to the networkService.
This is my network service, but i get an error of
Value of type '[String : Any]' has no member 'data'
on the line: let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
func request(json: [String:Any]) {
let url = URL(string: urlString)!
let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
var request = URLRequest(url: url)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
Alamofire.request(request).responseJSON {
(response) in
print(response)
}
}
The idea being I pass in my JSON when i call the func via the func parameter.
This is the JSON object passed in:
func loginUser(data: Array<String>, deviceToken: String) {
// create JSON
let json = [ "login-email" : data[0],
"login-password" : data[1],
"login-secret" : "8A145C555C43FBA5",
"devicetoken" : deviceToken
]
networkManager.request(json: json)
}
Then I convert and send it to the API (urlString)
Any idea if/why this isnt working?
THanks
Updated revision:
func request(json: [String:Any]) {
let url = URL(string: urlString)!
do {
let jsonData = try JSONSerialization.data(withJSONObject: json, options:[])
var request = URLRequest(url: url)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
Alamofire.request(request).responseJSON {
(response) in
print(response)
}
} catch {
print("Failed to serialise and send JSON")
}
}
update: added my code to make a call with completion question:
func sendLoginRequest() {
let userLogin = UserService.init(loginEmail: userEmail, loginPassword: userPassword, loginSecret: loginSecret, deviceToken: deviceToken)
networkService.logUserIn(request: userLogin) { (<#JSON?#>, <#NSError?#>) in
<#code#>
}
}
edit: Updated Payload Shot:
edit 2: mapping issue example:
init?(_ json: JSON) {
// Map API Key from top level
guard let apiKey = json["apikey"].string else { return nil }
// Map User at user level
guard let userDataArray = json["user"].array else {
fatalError("user data array NOT FOUND")
}
print("USER DATA IS \(userDataArray)")
// assign user
for child in userDataArray {
guard let userID = child["id"].int,
let userEmail = child["email"].string,
let lastName = child["lastname"].string,
let firstName = child["firstname"].string,
let company = child["company"].string,
let userImage = child["image"].string,
let jobTitle = child["jobtitle"].string
else { return nil
}
}
// Assign to model properties
self.apiKey = apiKey
self.userEmail = userEmail
self.lastName = lastName
self.firstName = firstName
self.company = company
self.userImage = userImage
self.jobTitle = jobTitle
self.userID = userID
}
I just show how I work with this.
You don't have to convert your parameters to JSON. It's code from Alamofire.
/// A dictionary of parameters to apply to a `URLRequest`.
public typealias Parameters = [String: Any]
Use this method instead of your:
Alamofire.request(url, method: method, parameters: parameters, encoding: encoding, headers: customHeaders)
Try this:
Instead of your request.httpBody = jsonData you can pass your json in parameters.
Your whole code will be:
func request(json: [String:Any]) {
Alamofire.request(urlString, method: .post, parameters: json, encoding: JSONEncoding.default).responseJSON {
(response) in
print(response)
}
}
If you are interested in my approach:
func makePick(request: MakePickRequest, completionHandler: #escaping APICompletionHandler) {
let parameters = request.converToParameters()
Alamofire.request(Endpoints.makePick, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
self.handleResponse(response: response, completionHandler: completionHandler)
}
}
Request:
struct MakePickRequest: GeneralRequest {
let eventId: Int64
let sportId: String
let pickType: PickType
let betType: BetType
let amount: Int
func converToParameters() -> [String : String] {
return ["event_id": String(eventId), "sport_id": sportId,
"pick_type": pickType.rawValue, "bet_type": betType.rawValue,
"amount": String(amount)]
}
}
Structure with endpoints:
struct Endpoints {
// Development baseURL
static let baseURL = "http://myurl/"
private static let apiVersion = "api/v1/"
static var fullPath: String {
return "\(baseURL)\(apiVersion)"
}
// MARK: - User endpoints (POST)
static var login: String {
return "\(fullPath)users/login"
}
static var signUp: String {
return "\(fullPath)users/signup"
}
...
}
Outside of any class (but import SwiftyJSON is obligatory):
typealias APICompletionHandler = (_ data: JSON?, _ error: NSError?) -> Void
Handle response:
private func handleResponse(response: DataResponse<Any>, completionHandler: APICompletionHandler) {
self.printDebugInfo(response)
switch response.result {
case .success(let value):
self.handleJSON(data: value, handler: completionHandler)
case .failure(let error):
print(error)
completionHandler(nil, error as NSError?)
}
}
private func handleJSON(data: Any, handler: APICompletionHandler) {
let json = JSON(data)
let serverResponse = GeneralServerResponse(json)
if (serverResponse?.status == .ok) {
handler(serverResponse?.data, nil)
} else {
handler(nil, self.parseJsonWithErrors(json))
}
}
GeneralServerResponse (depends on your server API):
import SwiftyJSON
final class GeneralServerResponse {
let data: JSON
let status: Status
init?(_ json: JSON) {
guard let status = json["status"].int else {
return nil
}
self.status = Status(status)
self.data = json["data"]
}
enum Status {
case ok
case error
case unauthorized
init(_ input: Int) {
if input >= 200 && input < 400 {
self = .ok
} else if input == 403 {
self = .unauthorized
} else {
self = .error
}
}
}
}
My actual example of usage.
This is outside:
func +=<K, V> ( left: inout [K : V], right: [K : V]) { for (k, v) in right { left[k] = v } }
Example of request:
func makePick(request: MakePickRequest, completionHandler: #escaping APICompletionHandler) {
var parameters = ["auth_token": Preferences.getAuthToken()]
parameters += request.converToParameters()
manager.apiRequest(url: Endpoints.makePick, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
self.handleResponse(response: response, completionHandler: completionHandler)
}
}
SessionManager extension to add headers for all requests:
extension SessionManager {
func apiRequest(url: URLConvertible, method: HTTPMethod, parameters: Parameters? = nil, encoding: ParameterEncoding, headers: HTTPHeaders? = nil) -> DataRequest {
var customHeaders: HTTPHeaders = ["api-key" : "1wFVerFztxzhgt"]
if let headers = headers {
customHeaders += headers
}
return request(url, method: method, parameters: parameters, encoding: encoding, headers: customHeaders)
}
}
In APIManager class:
private let manager: SessionManager
init() {
manager = Alamofire.SessionManager.default
}
Call example:
apiClient.makePick(request: request) { data, error in
if let error = error {
print(error.localizedDescription)
return
}
if let data = data {
// data is a JSON object, here you can parse it and create objects
}
}
Example of class:
import SwiftyJSON
final class MyClass {
let id: Int
let username: String
let parameter: Double
init?(_ json: JSON) {
guard let id = json["id"].int, let username = json["username"].string,
let parameter = json["parameter"].double else {
return nil
}
self.id = id
self.username = username
self.parameter = parameter
}
}

Swift Alamofire Request Error - Extra Argument in call

I am getting an error when I am trying to request using Alamofire. The error says that there is an 'extra argument in call'.
class SwiftStockKit {
class func fetchStocksFromSearchTerm(term: String, completion:#escaping (_ stockInfoArray: [StockSearchResult]) -> ()) {
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async {
let searchURL = "http://autoc.finance.yahoo.com/autoc"
Alamofire.request(.GET, searchURL, parameters: ["query": term, "region": 2, "lang": "en"]).responseJSON { response in
if let resultJSON = response.result.value as? [String : AnyObject] {
if let jsonArray = (resultJSON["ResultSet"] as! [String : AnyObject])["Result"] as? [[String : String]] {
var stockInfoArray = [StockSearchResult]()
for dictionary in jsonArray {
stockInfoArray.append(StockSearchResult(symbol: dictionary["symbol"], name: dictionary["name"], exchange: dictionary["exchDisp"], assetType: dictionary["typeDisp"]))
}
dispatch_async(dispatch_get_main_queue()) {
completion(stockInfoArray: stockInfoArray)
}
}
}
}
}
}
The line that is giving me an error is:
Alamofire.request(.GET, searchURL, parameters: ["query": term, "region": 2, "lang": "en"]).responseJSON { response in
if anyone could fix this I would be really grateful, thanks
Try change your request to something like this:
Alamofire.request(searchURL, method: .get, parameters: ["query": term, "region": 2, "lang": "en"], encoding: JSONEncoding.default, headers: nil)

Resources