如何使用alamofire post请求swift 3与Parameter和callback?

时间:2017-08-31 04:29:52

标签: ios swift3 alamofire

我正在使用此功能进行alamofire请求。请告诉我我做错了什么?

function getItem(callback){
  var itemsObj;
  $('.info').on('click', function(){
    itemsObj = {};
    $this = $(this);
    itemsObj.gameImg = $this.parent().parent().find('img').attr('src');
    itemsObj.gameTitle  = $this.parent().parent().find('h2').text();
    itemsObj.gameInfo = $this.parent().parent().find('p').text();
    // call the callback function parameter and send itemsObj as argument, callback function then received the argument as you wanted it to be. Then execute stuff from there.
    callback(itemsObj);
  });
}

// send a function instead for getItem to call when all is well
getItem(function (data) {
   // here you will receive the data
   console.log('from function:', data);
   localStorage.data = (JSON.stringify(data));
   if(localStorage.getItem("data")){
    var savedLocal = localStorage.getItem("data");
    savedLocal = JSON.parse(savedLocal);
    var favsResult = $('.favs-display-data');
     favsOutput = `<div class="col-lg-3 game">
                  <div class="view view-first">
                    <img src="${savedLocal.gameImg}"/>
                    <div class="mask">
                      <h2>${savedLocal.gameTitle}</h2> 
                      <p>${savedLocal.gameInfo}</p>
                      <a href="#" class="info">♥</a>
                    </div>
                  </div>
                </div>`
    favsResult.append(favsOutput);
   }
   console.log('savedLocal: ', savedLocal);

5 个答案:

答案 0 :(得分:2)

  

使用Almofire和SwiftyJSON,您可以轻松地调用JSON Formate

import Alamofire
import SwiftyJSON

//remoteLogin JSON Parsing
func remoteLogin()
{
    let params : Parameters = [
        "user": "username",
        "pass": "password"
    ]

    print("param is \(params)")

    let url = URL(string: "\(Constant.API)login")!
    print("Url printed \(url)")

    let manager = Alamofire.SessionManager.default
    manager.session.configuration.timeoutIntervalForRequest = 120

    manager.request(url, method: .post, parameters: params)
        .responseJSON
        {
            response in

            switch (response.result)
            {
            case .success:

                //do json stuff
                let jsonResponse = response.result.value as! NSDictionary
                print("JsonResponse printed \(jsonResponse)")

                //check authenticate is yes or no..
                let myInt: Bool = jsonResponse["authenticate"]! as! Bool

                if (myInt == true)
                {
                    //do Success stuff

                    //alertview
                    let alert = UIAlertController(title: Constants.APP_ALERT_TITLE, message: Constants.SUCCESS_MESSAGE, preferredStyle: UIAlertControllerStyle.alert)

                    DispatchQueue.main.async {
                        self.present(alert, animated: true, completion: nil)
                    }

                    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))
                }
                else
                {
                    //do Error stuff

                    //alertview
                    let alert = UIAlertController(title: Constants.APP_ALERT_TITLE, message: Constants.ERROR_MESSAGE, preferredStyle: UIAlertControllerStyle.alert)

                    DispatchQueue.main.async {
                        self.present(alert, animated: true, completion: nil)
                    }

                    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))
                }
                break

            case .failure(let error):

                if error._code == NSURLErrorTimedOut {
                    //HANDLE TIMEOUT HERE
                }

                let alert = UIAlertController(title: Constants.APP_ALERT_TITLE, message: Constants.ERROR_MESSAGE, preferredStyle: UIAlertControllerStyle.alert)

                DispatchQueue.main.async {
                    self.present(alert, animated: true, completion: nil)
                }

                alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))

                print("\n\nAuth request failed with error:\n \(error)")
                break
            }
    }
}

或使用包装器类,您可以轻松地调用Almofire API。 https://www.dropbox.com/s/2dvzr9rl6tt0ltt/HttpWrapperClass.zip?dl=0

  

或者如果使用SHOP API,则此处为代码。

let postString: NSMutableDictionary? = ["user_name":Txt_Login.text!,"password":Txt_Password.text!]

        let data = try! JSONSerialization.data(withJSONObject: postString!, options: JSONSerialization.WritingOptions.prettyPrinted)

        let request = NSMutableURLRequest(url: URL(string: "\(Constants.API)\(Constants.LOGIN)")!,
                                          cachePolicy: .useProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        request.httpMethod = "POST"
        let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
        request.httpBody = json!.data(using: String.Encoding.utf8.rawValue)

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
            if (error != nil) {
                DispatchQueue.main.async(){
                    AppDelegate.shared().HideHUD()
                }
            } else {
                AppDelegate.shared().HideHUD()
                let responseString = String(data: data!, encoding: .utf8)
                print("responseString = \(responseString!)")

                let Data = self.convertToDictionary(text: responseString!)
                print("Get Item \(Data!["data"]!)")

                let jsonResponse = Data!["data"]! as! NSArray

                let myInt: Bool = Data!["Success"]! as! Bool
                if (myInt == true)
                {

                }
                else{

                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        AppDelegate.shared().HideHUD()
                        AppDelegate.shared().ShowAlert(title: Constants.ERROR_HEADER, msg: Data!["Message"] as! String)
                    }
                }

            }
        })

        dataTask.resume()
    }

    func convertToDictionary(text: String) -> [String: Any]? {
        if let data = text.data(using: String.Encoding.utf8) {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
                print(json)
                return json
            } catch {
                print("Something went wrong")
            }
        }
        return nil
    }

答案 1 :(得分:1)

检查打印您的请求正文。您可以使用debugprint方法打印请求正文。

您也可以使用 Postman Google Chrome插件检查此请求正文。
仅用于交叉检查。

尝试以下代码: -

let _request = Alamofire.request(Url, method: .post, parameters: params, encoding: URLEncoding.httpBody)
        .responseJSON { response in
            switch response.result {
                case .success:
                    print("Validation Successful")
                    dic=(response.result.value) as! NSDictionary

                    var error = NSInteger()
                    error=dic.object(forKey: "error") as! NSInteger
                    completion(dic,error)

                case .failure(let error):
                    print(error)
                    completion(dic,0)
                }
        }
        debugPrint("whole _request ****",_request)

答案 2 :(得分:0)

试试这个:

Alamofire.request(url, method: .post, parameters: parameter).validate().responseJSON { response in
            switch response.result {
            case .success:
              if let result = response.result.value {
                 print("Validation Successful")
                dic=(response.result.value) as! NSDictionary
                var error = NSInteger()
                error=dic.object(forKey: "error") as! NSInteger
                completion(dic,error)
                }
            case .failure(let error):
                print(error)
                completion(dic,0)
            }
        }

答案 3 :(得分:0)

您没有收到响应,因为它是JSON格式。您将必须将JSON转换为Dictionary类型。

为此,您可以使用以下代码:

func convertToDictionary(_ string:String) -> [String: Any]? {
    if let data = string.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

要在您的代码中使用此代码,请执行以下操作:

func requestForLogin(Url:String,username: String,password: String, completion: @escaping (_ Dic: [String:Any]?,_ status:Int) -> Void) {
    var dic:[String:Any]?

    let params: Parameters = [
        "user": username,
        "pass": password
    ]

    Alamofire.request(Url, method: .post, parameters: params, encoding: URLEncoding.httpBody)
        .responseJSON { response in

            switch response.result {
            case .success:
                print("Validation Successful")
                dic = convertToDictionary(response.result.value as? String ?? "") as? [String:Any]
                var error = Int()
                error = dic["error"] as? Int ?? 0
                completion(dic,error)

            case .failure(let error):
                print(error)

                completion(dic,0)

            }
    }
}

在这里,我用[String:Any]代替了NSDictionary,用Int代替了NSInteger。同样,在这种情况下,您不应该使用强制拆包。所以我也改变了。

答案 4 :(得分:0)

Alamofire.request(URL + apiName, method: method, parameters: parameters).validate().responseJSON { response in
    switch response.result {
    case .success:
        if let json: NSDictionary = response.result.value as? NSDictionary{
            print(json)

        }else {
            completion(nil, NSError.init(domain: ErrorMessage, code: 0, userInfo: nil))
        }
    case .failure(let error):
        print (error)
        completion(nil, NSError.init(domain: ErrorMessage, code: 0, userInfo: nil))
    }