我在iOS的工作,當我把JSON DATAS,我沒有錯誤打印的功能,並添加一個字符串數組(我這樣做是正確的)的JSON值追加數組,但viewDidLoad中似乎空
但如果我想要達到字符串數組後來的JSON函數它似乎是空的數組。爲了測試,我在Button Action中打印了數組,然後它對我有效,但是當Json函數結束時,我想在其他函數的String Datas中使用它。
的代碼:
func getAllDataFromURL()
{
var i : Int = 0;
var urlDatas : [String] = allJsonDatas.getAllTours();
for(i = 0 ; i < allJsonDatas.getAllTours().count ; i += 1)
{
Alamofire.request(.GET, urlDatas[i]).responseJSON
{(response) -> Void in
if let arrivedData = response.result.value
{
print("********")
print(arrivedData["generalTourDistrict"] as! String);
print(arrivedData["otherTourDistrict"] as! String);
print(arrivedData["photoURLS"] as! [String]);
print(arrivedData["subTourDistrict"] as! String);
print(arrivedData["tourCalendar"] as! String);
print(arrivedData["tourDistrict"] as! String);
print(arrivedData["tourName"] as! String);
self.tryingSomething.appendContentsOf(arrivedData["photoURLS"] as! [String]);
print("********\n")
}
}
}
}
而且viewDidLoad中是
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.Request.addAcceptableImageContentTypes(acceptableContentTypes);
self.getAllDataFromURL();
self.printTheJsonDatas();
}
例如,在getAllDataFromURL()函數I可以正確打印。
這是用於從JSON URL數據的結果:
["https://acenta.dominant.com.tr//dominant/webout/R12/php/product/img.php?path=L2QvMS9jcmkvc295a3VsL3VydW4vMDAvMjIvMTIvaW1hZ2UvL3VfMDAyMjEyLjAwMDAxLmpwZWc=&rx=650&ry=400", "https://acenta.dominant.com.tr//dominant/webout/R12/php/product/img.php?path=L2QvMS9jcmkvc295a3VsL3VydW4vMDAvMjIvMTIvaW1hZ2UvL3VfMDAyMjEyLjAwMDA2LmpwZWc=&rx=650&ry=400"]
但是printTheJsonDatas()
打印空數組等 - > []
func printTheJsonDatas()
{
print(tryingSomething)
//tryingSomething : [String]
}
令人驚訝地,當我把printTheJsonDatas()
成buttonClickedAction
,然後它按照我之前說過的那樣工作。
我認爲問題是關於線程,但我不能說清楚什麼。
感謝您的評論sir,所以我需要在其他函數中使用json數據,tryingSomething是一個全局變量,我該怎麼辦? – elia
然後,您需要重寫'getAllDataFromURL()'以支持完成塊並在函數完成時調用它。請參閱https://thatthinginswift.com/completion-handlers/ for one,或谷歌「Swift Closures」或「Swift Completion Blocks」 – brandonscript
我使用完成塊「getAllDataFromURL()」編寫,但它不起作用,我猜json操作可行迅速和其他函數將數組作爲空數組 – elia