iOS开发技术iOSiOS开发资源

iOS开发拾记 -- 字典的遍历 & 简单的网络请求 &

2016-01-27  本文已影响250人  荒剑离

NSDictionary的遍历

//方法一
NSEnumerator *enum = [myDict keyEnumerator];
id key;
while ( key = [enum nextObject] ) {
   NSLog("%@ : %@", key, [myDict objectForKey:key]);
}
    
//方法二 
for (NSString *key in myDict) {
   NSLog("%@ : %@", key, [myDict objectForKey:key]);
}

简单的网络请求

// GET
NSString *urlStr = [NSString stringWithFormat:@"%@/food/?keyword=%@", baseURL, searchText];
NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
[conn start];

// POST
NSString *urlStr = [NSString stringWithFormat:@"%@/user/login", baseURL];
NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

NSString *dataStr = [NSString stringWithFormat:@"user_tel=%@&user_pass=%@", phone, password];
NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPBody:data];
[request setHTTPMethod:@"POST"];
[request setTimeoutInterval:5];

NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
[conn start];

别忘了实现网络请求代理方法:

#pragma mark - NSURLConnectionData Delegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    resultData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [resultData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"请求错误:%@", error);
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"请求失败"
                                                        message:@"网络堵车,请检查网络!"
                                                       delegate:self
                                              cancelButtonTitle:@"好"
                                              otherButtonTitles:nil, nil];
    [alertView show];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if (resultData.length > 0) {
        // type your code here ...
    }
}

如何在用户滚动UITableView时收起键盘

// UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [mySearchController.searchBar resignFirstResponder];
}

提示:UITableView继承自UIScrollView

上一篇 下一篇

猜你喜欢

热点阅读