2017-07-16 46 views
0

我是iOS開發新手。我在Android開發方面有一點經驗,並希望學習iOS開發。在Android中,我使用Retrofit庫來訪問API。訪問API的Swift庫

現在我想知道訪問API的類庫。我想討論一下具有良好性能,易於使用和易於理解的API庫。是的,當然,我已經試圖找到它,我明白了:

https://medium.com/ios-os-x-development/restkit-tutorial-how-to-fetch-data-from-an-api-into-core-data-9326af750e10

但我需要更多的想法有關庫訪問API,誰能幫助我?

謝謝。

回答

1

你可以在ios中使用Alamofire

Alamofire.request("https://httpbin.org/get").responseJSON { response in 
    print(response.request) // original URL request 
    print(response.response) // HTTP URL response 
    print(response.data)  // server data 
    print(response.result) // result of response serialization 

    if let JSON = response.result.value { 
     print("JSON: \(JSON)") 
    } 
} 
+0

如果API使用令牌訪問它呢? – Patrick

+0

使用HTTPHeaders –

+0

我已經試過這個庫,但我不明白將這個庫添加到我的項目。你能幫我解釋一下如何將這個庫添加到項目中嗎? – Patrick

2

在iOS中,唯一支持聯網的庫是Aalmofire。它簡化了所有的網絡通話鬥爭。它提供了訪問服務器數據的簡單方法。 Alamofireswift。如果要以目標C創建項目,則可使用目標C中提供的相同庫作爲AFNetworking

下面是編寫API調用的例子:

let url = "" 
let headers = [ "Content-Type" : "application/json"] 
let para : Parameters = [ "data" : JSONObject] 
Alamofire.request(url, method: .post, parameters: para, encoding: JSONEncoding.default, headers : headers) 
    .responseJSON { response in 

     print(response) 
     print(response.result) 

} 

注:當你是一個初學者我沒有告訴URLSessions(由蘋果公司提供的),這是寫作的最佳方式API調用。但這是未來的一個很好的選擇。

+0

如果您在標頭中使用訪問令牌。只需簡單地在標題中添加一個併發送它。 –

1

即使Alamofire看起來像是一個很好的聯網選擇,本地URLSession以及Codable protocol提供了相同的功能,而無需添加任何依賴項目。

let task = URLSession.shared.dataTask(with: url) { data, response, error in 
    // Handle data, response, and error 
} 

task.resume()