【问题标题】:How to HTTP Request in Swift 2.0 (Xcode 7.2)如何在 Swift 2.0 (Xcode 7.2) 中进行 HTTP 请求
【发布时间】:2016-02-26 12:10:35
【问题描述】:

我正在尝试向 Web 服务发出 http 请求。它返回 JSON 数据。我也想解析这些数据。我是 swift 的新手,我尝试了很多方法,但一无所获。这是我的服务地址:

http://xxx.xxx.xxx.xxx/mobileservice/login/firmcode/mailaddress/password/ip

我正在尝试在此 uri 模板上调用服务。我该怎么做有人可以帮忙吗?

【问题讨论】:

    标签: xcode swift web-services swift2


    【解决方案1】:

    发送 http 请求的一个好方法是 alamofire。尽管您也可以在没有外部库的情况下发送 http。看这段代码

    func sendHttpRequests(data : Dictionary<String, AnyObject>)
    {
     let url = NSURL ( string : "http://xxx.xxx.xxx.xxx/mobileservice/login/firmcode/mailaddress/password/ip")!
        let request:NSMutableURLRequest = NSMutableURLRequest(URL : url)
    
        //Data that you want to send
        let payload = "{r: typeRequest, e: object, p: anotherObject}"
        //js_object is the key that is configured in your server
        let bodyData = "{js_object:\(payload)}"
        //Setting httpMethod
        request.HTTPMethod = "POST"
    
        request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
    
    
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
            {
                (response, data, error) in
    
                //If response code is 200 you send the request successfully         
                if let httpResponse = response as? NSHTTPURLResponse {
                    let responseCode = httpResponse.statusCode
                    print(responseCode)
                }
                do
                {
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
    
    
                    print("Json sent by server\(json)")
    
                    if let value = json["myKey"] as? String
                    {
    
                        print(value)
                    }
                }
                catch
                {
                    print(error)
                }
    
    
        }
    }
    

    注意服务器发送的json是否是合法的json 这是php中的示例

    <?php
    $arr = array('myKey' => "ciao", 'b' => 2, 'c' => 3, 'd' => 4);
    
    echo json_encode($arr);
    ?>
    

    【讨论】:

    • 如何调用这个方法?我在 viewDidLoad sendHttpRequests(data: Dictionary) 调用这个数据应该是什么?
    • 对不起,数据应该等于有效负载,当您单击按钮或在 viewDidLoad 中调用此方法并传入有效负载您想要的请求
    • 你能说的更清楚一点吗?我是 swift 新手,现在不知道如何调用函数
    • 您可以删除:“data: Dictionary”并使用:sendHttpRequest() 调用此函数。但是这个函数总是传递这个通用的有效载荷: let payload = "{r: typeRequest, e: object, p: anotherObject}" 如果你想传递例如 username.text 和 password.text 你可以创建一个字典并传递这个作为论据
    • 非常感谢你太棒了我正在尝试这个但现在它给出了错误:缺少参数我该如何解决这个问题。
    【解决方案2】:

    https://github.com/Alamofire/Alamofire

    +

    https://github.com/SwiftyJSON/SwiftyJSON

    前:

    Alamofire.request(.GET, "http://xxx.xxx.xxx.xxx/mobileservice/login/firmcode/mailaddress/password/ip", parameters: nil)
         .responseJSON { response in
             print(response.request)  // original URL request
             print(response.response) // URL response
             print(response.data)     // server data
             print(response.result)   // result of response serialization
    
             if let res= response.result.value {
                 print("JSON: \(JSON)")
                 //Here you can parse the json with swiftyJSON
                 let json = JSON(res)
                 let name = json["name"].string
             }
         }
    

    【讨论】:

    • 如何将 Alamofire 导入我的项目?(我不会如何导入外部库)
    • 唯一的解决方案是按照下面链接中描述的过程进行操作 - 但是是的,您必须添加此外部库:/ 这将为您节省大量时间。
    【解决方案3】:

    正如 Benobab 所说,您可以使用像 Alamofire 这样的第三方框架。使用NSURLSessionNSURLSessionTask 也很容易做到这一点。 NSURLSession 有一个方法 sharedSession 可以为您提供一个已经配置好的会话。然后你想创建一个NSURLSessionDataTask。查看 Xcode 文档了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-10
      • 2021-10-26
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多