2017-10-18 87 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

相关问题