在swift 中 使用AFNetworking獲取json資料
首先要用到的東西就是把以前用的json資料在蘋果中呼叫回來,昨天終於可以在swift中使用 AFNetworking了,但是呼叫的時候發現,呼叫公開的返l回json的內容是沒有問題的,自己寫的服務,呼叫時卻顯示:Error: Request failed: unacceptable content-type: text/plain
這個應該是格式 的問題,於是baidu一下,找到了這篇文章:http://www.haogongju.net/art/2407859
使用AFNetworking 2.0 請求資料時出現錯誤 Request failed: unacceptable content-type: text/html 解決方法
新增一行
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
那我的是text/plain的錯,應該把相應內容html改為plain就可以了,
但是還有一個問題,這個NSSet型別,在swift中怎麼用呢,不知道
按下commond鍵,找一下幫助,前面的也看不太明白,看到這一段:
extensionNSSet {
var allObjects: AnyObject[]! { get }
func anyObject() -> AnyObject
func containsObject(anObject: AnyObject!) -> Bool
var description: String! { get }
func descriptionWithLocale(locale: AnyObject!) -> String!
func intersectsSet(otherSet: NSSet!) -> Bool
func isEqualToSet(otherSet: NSSet!) -> Bool
func isSubsetOfSet(otherSet: NSSet
func makeObjectsPerformSelector(aSelector: Selector)
func makeObjectsPerformSelector(aSelector: Selector, withObject argument: AnyObject!)
func setByAddingObject(anObject: AnyObject!) -> NSSet!
func setByAddingObjectsFromSet(other: NSSet!) -> NSSet!
func setByAddingObjectsFromArray(other: AnyObject[]!) -> NSSet!
func enumerateObjectsUsingBlock(block: ((AnyObject!, CMutablePointer<ObjCBool>) -> Void)!)
func enumerateObjectsWithOptions(opts: NSEnumerationOptions, usingBlock block: ((AnyObject!, CMutablePointer<ObjCBool>) -> Void)!)
func objectsPassingTest(predicate: ((AnyObject!, CMutablePointer<ObjCBool>) -> Bool)!) -> NSSet!
func objectsWithOptions(opts: NSEnumerationOptions, passingTest predicate: ((AnyObject!, CMutablePointer<ObjCBool>) -> Bool)!) -> NSSet!
}
其中有一個func setByAddingObject(anObject: AnyObject!) -> NSSet! 這個是返回一個NNSet的,應該可以用,於是就有了以下程式碼:
@IBAction func showimage(sender : AnyObject) {
let manager = AFHTTPRequestOperationManager()
let url = "http://api.openweathermap.org/data/2.5/weather"
let ul="http://218.3.208.82:800/goldnurse/OFFER.GetOfferList.do"
println(url)
let params = ["lat": 39.26, "lon": 41.03, "cnt":0]
println(params)
var type="text/plain"
var sets=NSSet()
manager.responseSerializer.acceptableContentTypes = sets.setByAddingObject(type)
//[NSSet setWithObject:@"text/html"]
manager.GET(ul,
parameters: params,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
println("JSON: " + responseObject.description!)
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
})
}
居然成功的返回了我自己寫的json資料!!但是返回的內容中,中文部分是編碼的,不知道如何把這些內容再轉成中文。