0

我一直在尝试调整 NSURLSession 类方法 dataTaskWithRequest 但无法完成

extension NSURLSession{
public override class func initialize() {
    struct Static {
        static var token: dispatch_once_t = 0
    }

    if self !== NSURLSession.self {
        return
    }

    dispatch_once(&Static.token) {
        let originalSelector = Selector("dataTaskWithRequest:completionHandler:")
        let swizzledSelector = Selector("my_dataTaskWithRequest:completionHandler:")

        let originalMethod = class_getInstanceMethod(self, originalSelector)
        let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)

        let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))

        if didAddMethod {
            class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod)
        }
    }
}

// Swizzled Method
func my_dataTaskWithRequest(request: NSURLRequest,completionHandler: (NSData?, NSURLResponse?, NSError?)) -> NSURLSessionDataTask {

    print("Inside Swizzled Method")

    return my_dataTaskWithRequest(request,completionHandler: completionHandler)
}
}

提前致谢 !!

4

2 回答 2

-1

我必须以 JSON(或 NSDictionary )格式将我的数据上传到服务器。
我做过这样的事情......

let urlPath:String = apiURL + apiVersion + url + "?api_key=" + apiKey
//  OR
let urlPath:String = "your url string"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()

let task = session.dataTaskWithURL(url!, completionHandler: {(data, reponse, error) in
println("Task completed")
// rest of the function...
})

task.resume()


有关更多或相关答案,请访问链接
如何在私有方法中调酒

我希望它可以帮助你

于 2016-02-25T14:39:30.280 回答
-1
// i hope it may be help you
  extension NSURLSession{
  public override class func initialize() {
   struct Static {
      static var token: dispatch_once_t = 0
   }

  if self !== NSURLSession.self {
      return
  }

  dispatch_once(&Static.token) {
 let method1: Method = class_getInstanceMethod(self,Selector("dataTaskWithRequest:completionHandler:"));
 let method2 = class_getInstanceMethod(self, Selector("my_dataTaskWithRequest:completionHandler:"));
  method_exchangeImplementations(method1, method2);
}
}
// Swizzled Method
func my_dataTaskWithRequest(request: NSURLRequest,completionHandler: (NSData?, NSURLResponse?, NSError?)) -> NSURLSessionDataTask {

print("Inside Swizzled Method")

return my_dataTaskWithRequest(request,completionHandler: completionHandler)
}
}
于 2016-02-26T14:08:10.753 回答