2017-10-18 59 views
-1

我面對一個問題,我嘗試了不同的解決方案,但是我還是無法解決。問題是Instance member 'decodeJson' cannot be used on type 'Utils'decodeJson區域。正如你可以看到的Utils類具有不同的功能,其中getDataWithURLSession,decodeJsongetDataWithURLSession需要使用decodeJson實例成員'decodeJson'不能在類型'Utils'上使用

public class Utils { 

    static var ApiURL = "http://xxx" 

    var categoryList = [MangaCategory]() 

    //MARK - JSON Searilization 
    @available(iOS 10.0, *) 
    static func getDataWithURLSession(withtoken: String){ 
     guard let url = URL(string: Utils.ApiURL + "/Category/Get") else {return} 
     var request = URLRequest(url: url) 

     request.httpMethod = "POST" 
     request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
     request.setValue("Bearer " + withtoken, forHTTPHeaderField: "Authorization") 

     guard let httpBody = try? JSONSerialization.data(withJSONObject: [], options: []) else { return } 
     request.httpBody = httpBody 

     let task = URLSession.shared.dataTask(with: request) { (data, response, err) in 

      decodeJson(data: data) 
     } 
     task.resume() 
    } 

    @available(iOS 10.0, *) 
    private func decodeJson(data:Data?){ 
     guard let data = data else {return} 
     dump(data) 

     do { 
      let json = try JSONDecoder().decode(Categorys.self, from: data) 
      for manga in json.data{ 
       if json.data.count > categoryList.count 
       { 
        let cat = MangaCategory(context: CoreDataService.context) 

        cat.category_name = manga.name 
        cat.category_id = Int16(manga.id)! 

        CoreDataService.saveContext() 
        self.categoryList.append(cat) 
       } 
       else{ 
        print("JSon Serialization Es Geçildi.") 
       } 
      } 

     } catch let jsonError { 
      print("JSON Serializing error : ", jsonError) 

     } 
    } 
} 

回答

0

如果我收到了你的問題吧,你要使用的utils的類的實例的私有方法在沒有定義的實例類的方法。

爲了解決它,你有幾種選擇:

  1. 使這兩種方法是實例方法(先做出一家不是靜態的,而是公衆)。

  2. 使這兩種方法都是Utils類方法 - 使第二個函數也是靜態的。但是在這種情況下,您將不得不在方法decodeJson中返回Utils類的實例,以便能夠在其中存儲categoryList變量。

如果你決定使用第二個選項,並在代碼中的問題,讓我知道,我會在我的答案

+0

由於添加代碼。我試過第一個解決方案,但沒有工作所以,我改變了函數的名稱 'static func getDataWithURLSession(withtoken:String){'到 'public func getDataWithURLSession(withtoken:String){'和 'private func decodeJson(data:Data?){'到 ' public func decodeJson(data:Data?) - > [Any]'並添加'return categoryList'。其實我的utils類問題已解決,但當我在AppDelegate.swift調用getDataWithURLSession函數時,我看到不同的問題,例如'實例成員'getDataWithURLSession'不能用於類型'Utils';你的意思是使用這種類型的值嗎?' – Guray

+0

這兩個選項都取決於你將在哪裏使用Utils對象和存儲屬性。爲什麼第一種方法不起作用?我認爲你需要有一個對象,並通過調用getDataWithURLSession來填充它的categoryList。您能否在應用程序代理和其他任何地方顯示您使用的代碼?我的意思是你將如何使用它。我認爲你將它稱爲類方法,而我們正在試圖將它作爲一個實例。 – Woof

相關問題