2016-05-26 12 views
0

私のテーブルビューで使用するJSONファイルからデータをロードしようとしています。それにもかかわらず、viewdidloadでこの関数を呼び出すと、データを含む配列にデータが含まれず、空の配列が返されます。関数は空ではなく空の配列を返します。

class CompanyModel { 

func getJSON() -> NSMutableArray() { 

let companyArray: NSMutableArray = NSMutableArray() 

let requestURL: NSURL = NSURL(string: "http://localhost/Companies/JSON.php")! 
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL) 
let session = NSURLSession.sharedSession() 

let task = session.dataTaskWithRequest(urlRequest) { <- does not enter bracket? 
    (data, response, error) -> Void in 

    let httpResponse = response as! NSHTTPURLResponse 
    let statusCode = httpResponse.statusCode 

    if (statusCode == 200) { 
     print("Everyone is fine, file downloaded successfully.") 

     do{ 

      let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) 

      if let companies = json["companies"] as? [[String: AnyObject]] { 

       for company in companies { 

        if let name = company["name"] as? String, 
         let phoneNumber = company["phone_number"] as? String, 
         let website = company["website"] as? String, 
         let email = company["email"] as? String, 
         let address = company["address"] as? String 

        { 
        let company = CompanyModel() 

         company.name = name 
         company.phoneNumber = phoneNumber 
         company.website = website 
         company.email = email 
         company.address = address 
        } 
        companyArray.addObject(company) 
        print(companyArray) 
       } 
      } 
     } catch { 
      print("Error with Json: \(error)") 
     } 

    } 
    print(companyArray) <- array is populated 
} 
print(companyArray) <- array is empty 
task.resume() 
return companyArray 
} 
} 

私がデバッグセッションを実行すると、上記のブラケットには入りません。代わりに、関数を返すようにまっすぐジャンプし、空の配列を返します。私はJSONファイルからデータを取得することはできないと信じていますが、それほど理由はわかりません。

+0

があなたのJSONを印刷してみてください役立ちます

希望は、あなたは、有効なデータを得るのですか?ただ確実にする。 また、Jsonデータを共有することができれば、答えが簡単かもしれません。 「企業」はjsonの直接の鍵ではないかもしれないので、jsonの鍵の鍵となるかもしれない。 –

+0

jsonデータを印刷し、有効なjsonをチェックするかどうか –

答えて

0

第2のprint(companyArray)コードが実行され、要求がバックグラウンドタスクとして実行されるため、サーバーからのデータが返されます。成功コードの内部にreturn companyArrayと書かなければなりません。それ以外の場合は、returnは配列を空にしてください。

0

コードでは、別のスレッドで実行されるデータタスクを作成しました。

print(companyArray) <- this one is after request returns a response 
} 
print(companyArray) <- this comes before the array is populated 
task.resume() <- And here is where you start the data task 
return companyArray 

論理を変更して、メソッドの完了時にcompanyArrayを返すことができます。あなたのコードlocalhost

print(companyArray) <- and for the love of God, don't put return here! 
} 
print(companyArray) <- this comes before the array is populated 
task.resume() <- And here is where you start the data task 
return companyArray 
0

問題を作成している、あなたはnilとしてresponseを取得します。したがって、何かを確認する前に、print(data)print(response)print(error)の方が良いです。このURLをご利用になる場合は、https://httpbin.org/get以降のURLのlocalhostIPまたはdomainに置き換えてください。ここで

は、上記の更新コードです:doc of NSURLSessionから

func getWebServiceWithURL(strUrl: String, completionHandler: (NSDictionary?, NSError?) ->()) ->(){ 

    let getTask = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: strUrl)!) { (responseData, _, error) -> Void in 

     dispatch_async(dispatch_get_main_queue(), {() -> Void in 

      do{ 
       if responseData != nil{ 

        let json = try NSJSONSerialization.JSONObjectWithData(responseData!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary 

        if let parseJSON = json { 

         // Parsed JSON 
         completionHandler(parseJSON, nil) 
        } 
        else { 
         // Woa, okay the json object was nil, something went worng. Maybe the server isn't running? 
         let jsonStr = NSString(data: responseData!, encoding: NSUTF8StringEncoding) 

         #if DEBUG 
          print("Error could not parse JSON: \(jsonStr)") 
         #endif 
        } 
       }else{ 

        completionHandler(nil, error) 
       } 

      }catch let error as NSError{ 

       print(error.localizedDescription) 
       completionHandler(nil, error) 
      } 
     }) 
    } 

    getTask.resume() 
} 
0

一部:

ほとんどのネットワークAPIと同様に、NSURLSessionのAPIは非常に 非同期です。それはあなたが呼び出す方法に応じて2つの方法のいずれか、 であなたのアプリにデータを返します。

To a completion handler block that is called when a transfer finishes successfully or with an error. 

By calling methods on the session’s delegate as data is received and when the transfer is complete. 

とあなたのコードから一部:

print(companyArray) <- array is populated 
} 
print(companyArray) <- array is empty 

あなたはあなたの完了の内側companyArrayを読み込まれますハンドラは非同期プロセスが完了すると終了し、完了ハンドラの外側では空です。コード:

print(companyArray) <- array is empty 
このラインに非常に隣の

実行:

let task = session.dataTaskWithRequest(urlRequest) { 

と完了ハンドラがまだ評価されていません。完了ハンドラを消費して実際の結果を得る。

0

return companyArray応答がサーバーから送信される前に呼び出されます。配列のような戻り値の型でメソッドを作成すべきではありません!companyArrayをパブリック変数またはインスタンス変数とし、webservice呼び出しの完了ブロックからその値を設定し、必要な場所で使用することができます。これは:)

関連する問題