向API发送和检索数据在swift中

时间:2015-03-16 06:15:09

标签: swift

我已经使用委托方法从API读取了数据...但我不明白如何将数据发送回API


这是我从API读取数据的代码。

func getDataFromAPI()
{
    var strApi : String = "http://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=transit&origin=woottonbridge+UK&destination=ashfordinternational+UK&arrival_time=1415358000&alternatives=true"
    var url  = NSURL(string: strApi)
    var request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "GET"
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler: {(response : NSURLResponse! , data : NSData! , error : NSError!) -> Void in

   var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
    let jsonDictionary: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
        if jsonDictionary != nil
        {
           var arrayData : NSArray = jsonDictionary.objectForKey("routes") as NSArray
            println("\(arrayData[0])")
        }
    })
}

2 个答案:

答案 0 :(得分:0)

使用NSURLConnection和http方法&#34; POST&#34;,你可以添加你想要发送到内部API的内容&#34; BODY&#34;请求。

或者正如Dato所说,你可以选择Alamofire,总是最好的选择:)

调查 - How to make an HTTP request in Swift?How to create and send the json data to server using swift language

一切顺利

答案 1 :(得分:0)

您可以尝试使用此合并AlamofireSwiftyJSON

import UIKit
import Alamofire
import Haneke

class MatchTableViewController: UITableViewController {

    var datas: [JSON] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request(.GET, "http://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=transit&origin=woottonbridge+UK&destination=ashfordinternational+UK&arrival_time=1415358000&alternatives=true").responseJSON { (request, response, json, error) in
            if json != nil {
                println(json)
            }
        }
    }
}

参考:http://blog.revivalx.com/2015/02/24/uicollectionview-tutorial-in-swift-using-alamofire-haneke-and-swiftyjson/