我試圖實現雨燕下面的代碼的PUT版本(這樣我就可以實現一個PUT
附件),網址爲:https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFHTTPSessionManager.m翻譯AFNetworking POST constructingBodyWithBlock從目標C斯威夫特
我有麻煩讓它編譯,它說變量task
是used within its own initial value
。有什麼想法嗎?
目標C
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
if (serializationError) {
if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
#pragma clang diagnostic pop
}
return nil;
}
__block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
if (error) {
if (failure) {
failure(task, error);
}
} else {
if (success) {
success(task, responseObject);
}
}
}];
[task resume];
return task;
}
斯威夫特
func PUT(URLString: String!, parameters: AnyObject!, constructingBodyWithBlock block: ((AFMultipartFormData!) -> Void)!,
success: ((NSURLSessionDataTask!, AnyObject!) -> Void)!,
failure: ((NSURLSessionDataTask!, NSError!) -> Void)!) -> NSURLSessionDataTask! {
let urlX = "http://localhost/\(URLString)" //still need to convert to baseURL
var serializationError:NSErrorPointer = nil
let request:NSMutableURLRequest = self.requestSerializer.multipartFormRequestWithMethod("PUT", URLString: urlX, parameters: parameters as! [NSObject : AnyObject]!, constructingBodyWithBlock: block, error: serializationError)
let task:NSURLSessionDataTask = self.uploadTaskWithStreamedRequest(request, progress: nil, completionHandler: { (response: NSURLResponse!, responseObject: AnyObject!, error: NSError!) -> Void in
if ((error) != nil) {
if ((failure) != nil) {
failure(task, error) <-- error
}
} else {
if ((success) != nil) {
success(task, responsObject) <-- error
}
}
})
我試圖實現與附件,類似與constructingBodyWithBlock爲POST PUT,但AFNetworking沒有它的PUT版本。 – Dean
好的,夠公平的。讓我加載了一個項目,看看我找到:) – ArtSabintsev
好吧,我覺得問題是,在斯威夫特你想使用它自己的定義中恆'task',因此誤差範圍內***變量用於其自己的初始值***。讓我再修補一下。 – ArtSabintsev