Reputation: 30023
I'm trying to translate this class from Objective-C to Swift. I'm almost done except for this method:
-(void) handleCookiesInRequest:(NSMutableURLRequest*) request
{
NSURL* url = request.URL;
NSArray* cookies = [self cookiesForURL:url];
NSDictionary* headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
NSUInteger count = [headers count];
__unsafe_unretained id keys[count], values[count];
[headers getObjects:values andKeys:keys];
for (NSUInteger i=0;i<count;i++) {
[request setValue:values[i] forHTTPHeaderField:keys[i]];
}
}
My attempt:
func handleCookiesInRequest(request: NSMutableURLRequest) {
var url = request.URL
var cookies = self.cookiesForURL(url!)
var headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)
var count = headers.count
for i in 0...count {
request.setValue(value: headers.values[i], forHTTPHeaderField: headers.keys[i])
}
}
I get an error in the line that set value saying
CustomHTTPCookieStorage.swift:88:21: Type '(value: $T8, forHTTPHeaderField: $T21)' does not conform to protocol '_SignedIntegerType'
Can you help me?
Upvotes: 2
Views: 648
Reputation: 299345
NSHTTPCookie.requestHeaderFieldsWithCookies()
returns a dictionary, not an array. You meant this:
for (key, value) in headers {
request.setValue(value as? String, forHTTPHeaderField: key as! String)
}
You can make this a bit safer this way:
if let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies) as? [String:String] {
for (key, value) in headers {
request.setValue(value, forHTTPHeaderField: key)
}
}
Of course, if you haven't set any headers yet, this can all be replaced with:
request.allHTTPHeaderFields = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)
But this will blow away any preset headers, so the semantics are a little different.
Upvotes: 3