Merge: doc: fixed some typos and other misc. corrections
[nit.git] / lib / ios / http_request.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Implementation of `app::http_request` for iOS
16 module http_request
17
18 import ios
19 import cocoa::foundation
20 intrude import app::http_request
21
22 redef class App
23 redef fun run_on_ui_thread(task) import Task.main in "ObjC" `{
24 Task_incr_ref(task);
25 dispatch_async(dispatch_get_main_queue(), ^{
26 Task_main(task);
27 Task_decr_ref(task);
28 });
29 `}
30 end
31
32 redef class Text
33 redef fun http_get
34 do
35 var error_ref = new Ref[NSString]("Unknown Error".to_nsstring)
36 var data = to_nsstring.native_http_get(60.0, error_ref)
37
38 if data.address_is_null then
39 # There was an error
40 var error = new IOError(error_ref.item.to_s)
41 return new HttpRequestResult(null, error)
42 else
43 # TODO use the real return code instead of 200
44 return new HttpRequestResult(data.to_s, null, 200)
45 end
46 end
47 end
48
49 redef class NSString
50 private fun native_http_get(timeout: Float, error_ref: Ref[NSString]): NSData
51 import Ref[NSString].item= in "ObjC" `{
52
53 NSURL *url = [NSURL URLWithString:self];
54 NSURLRequest *request = [NSURLRequest requestWithURL:url
55 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:timeout];
56
57 NSURLResponse *response = nil;
58 NSError *error = nil;
59 NSData *data = [NSURLConnection sendSynchronousRequest:request
60 returningResponse:&response error:&error];
61
62 if (data == nil) {
63 // Report error
64 Ref_of_NSString_item__assign(error_ref, [error localizedDescription]);
65 return nil;
66 }
67
68 return data;
69 `}
70 end