我想知道如何使用停留在do-catch語句中的變量。我從網上解析一些JSON並用它填充一個對象,但之後我需要外部的對象來填充UITableView。該功能從哪裏獲得網絡信息:在swift中使用do-catch語句獲取變量
func post(dburl: String, info: String, completionHandler: (NSString?, NSError?) ->()) -> NSURLSessionTask {
let myUrl = NSURL(string: dburl)!;
let request = NSMutableURLRequest(URL:myUrl);
request.HTTPMethod = "POST";
let postString = info //finalPlaceId = info
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{ data, response, error in dispatch_async(dispatch_get_main_queue()) {
guard data != nil else {
completionHandler(nil, error)
return
}
completionHandler(NSString(data: data!, encoding: NSUTF8StringEncoding), nil)
}
}
task.resume()
return task
}
因此,我調用函數裏面我做的做副漁獲物:
post(dburl, info: finalPlaceId) { responseString , error in
guard responseString != nil else {
print(error)
return
}
do { if let dataDB = responseString!.dataUsingEncoding(NSUTF8StringEncoding) {
var error: NSError?
let jsonDB = try NSJSONSerialization.JSONObjectWithData(dataDB, options:[])
//print(jsonDB)
if let infoArray = jsonResults["results"] as? [NSDictionary] {
if let infoArrayDB = jsonDB as? [NSDictionary] {
for item in infoArray {
for item2 in infoArrayDB {
self.JSON_Info.append(JSONInfo(json: item))
self.JSON_Info.append(JSONInfo(json: item2))
}
}
print(infoArrayDB)
}
}
}
} catch { print("Fetch Failed:\(error as NSError).localizedDescription)")
}
// print(responseString!)
}
是否有可能現在使用JSON_Info了這個功能呢?如果不是,即使採用其他變量也足夠了,所以我可以在函數中執行for循環。理想情況下,我想使用函數中的infoArray和infoArrayDB。我感謝您的幫助。
如果我的答案解決您的問題,然後接受我的答案。謝謝。 – Bhoomi
非常感謝。這工作完美 – manhols
嗨bhoomi多一個問題。實際上,它完全脫離了do-catch(這是原始問題),但我仍然無法將它用於函數外,我假定它調用異步任務?我需要用函數的信息來填充表格視圖,但它不在其外面。你會推薦什麼? – manhols