FAQ Database Discussion Community


I am not able to get data from my localhost using this code. Please help me. I am getting nil

ios,swift,nsurl
var data = NSData(contentsOfURL: NSURL(string: "www.google.com")!) println(data) After using this line of code in playground I am getting nil value for data. So how do I get a value. My real URL is: 192.168.1.8:8888/service.php (this url is showing JSON data in the browser) But I am not able to get...

Program skips NSURLRequest used to download txt file, if placed in IB action with other code

ios,objective-c,curl,nsurl
I am using a NSURL request in objective -c in order to download a webpage and place it in a text file. This is similar to the curl function used in UNIX. Here is the code: NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSString *filePath = [documentDir stringByAppendingPathComponent:@"data.txt"]; NSURLRequest *request...

Convert String to NSURL is return nil in swift

string,swift,nsurl
I am trying to convert a String to NSURL and my code for that is Below: var url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitude),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US" println("This is String: \(url)") var remoteUrl : NSURL? = NSURL(string: url) println("This is URL: \(remoteUrl)") And console prints something like this: This is String:...

Strange Invisible Character in String causing NSURL to fail

ios,string,swift,nsurl,addressbook
I am having a String to Number problem that is taking me days to resolve. So it all started out in my app that involves taking a phone number from the addressbook and making a call. Everything was working fine until I noticed some phone numbers were causing my program...

How do I get the NSURLResponse before the downloadTaskWithURL finishes?

ios,swift,nsurl,nsurlsession
This is my code for download : let url = NSURL(string:"http://www.zastavki.com/pictures/originals/2013/Photoshop_Image_of_the_horse_053857_.jpg")! let documentsDirectoryURL = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL NSURLSession.sharedSession().downloadTaskWithURL(url, completionHandler: { (location, response, error) -> Void in if let error = error { println(error.description) } else { println("Finished downloading \"\(response.suggestedFilename)\".") println(location.path!)...

Not downloading files to NSDocumentsDirectory correctly?

ios,swift,download,nsurlconnection,nsurl
I want to download files to my NSDocumentsDirectory. I grab a url that is a download link and that url is stored into a variable called url Here is my code to perform the download and store it into the Documents Directory so: let data = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: &response,error: &error)...

How to show the image via http url in AlertView in Objective-C?

ios,objective-c,uiimage,uialertview,nsurl
I am developing in Objective-C , and I want to show the image via http url in AlertView ? I already get the image url like:http://192.72.1.1/DCIM/100__DSC/SNAP0053.JPG , and convert the NSURL to NSString. But I can not show the image in AlertView , it is empty. The code for convert...

%2C in NSURLComponents turns to %2525252C - swift

ios,api,swift,nsurl
I'm using NSURLComponents to generate a URL for an API call in Swift: func generateSearchByLocaleURL(lat: Int, lon: Int) -> String { var components = NSURLComponents() let bbox = generateBboxValue(lat, lon) components.scheme = "https" components.host = "api.flickr.com" components.path = "/services/rest/" components.queryItems = [ NSURLQueryItem(name: "method", value: "flickr.photos.search"), NSURLQueryItem(name: "api_key", value: "KEY_VALUE"),...

NSURL with string relative to URL returning unexpected result

ios,xcode,afnetworking-2,nsurl
This is the call I am making: NSURL *url = [NSURL URLWithString:@"rooms" relativeToURL:[NSURL URLWithString:@"localhost:9000"]]; and the result of url.absoluteURL is: localhost:///rooms does this make sense? I was expecting the result to be localhost:9000/rooms Thanks!...

NSData is returning nil for same file at different filepaths

ios,objective-c,ios-simulator,nsdata,nsurl
I stored an audio file of format .aiff in two different folders. The NSData is returning nil for one file path even though both file paths have the audio file. I double checked the file paths. The path is like this: //url1 file:///Users/VenkataManiteja/Library/Developer/CoreSimulator/Devices/80B8117E-D2C9-4B42-8A76-9A89A10FB1C1/data/Containers/Data/Application/FD17AD64-EAF9-4578-B50D-0B5BF6F2DEFF/Documents/28Apr15_090827AM.aif //url2...

NSURL found nil while unwraping an Optional value

swift,nsurl,nsurlrequest
Anyone knows why am I getting fatal error: unexpectedly found nil while unwrapping an Optional value When i use let URL = NSURL(string: "https://roads.googleapis.com/v1/snapToRoads?path=-35.27801,149.12958|-35.28032,149.12907")! ...

Remove port from NSURL

objective-c,cocoa,nsurl
How can one normalise an NSURL, removing the port in particular? http://en.wikipedia.org/wiki/URL_normalization

How do I get the data from an NSURLSession as a string?

ios,swift,nsurl,nsurlsession
I'm using an API that gives me data in a neat format - How do I get this as a String? I can print it, but saving it as a string doesn't seem to work. I specifically want to update a UI element using the data from the NSURLSession task....

Saving an array of NSURL to NSUserDefaults

swift,nsuserdefaults,nsurl
I have an array of NSURL items like this: var array = [NSURL]() I'm trying to save this to NSUserDefaults: let defaults = NSUserDefaults(suiteName: "group.a.project") defaults?.setObject(array, forKey: "NSURLarray") Will result in it crashing as NSURL can't be stored in NSUserDefaults. How can I save this array of NSURL's to NSUserDefaults,...

Get position of NSString in string - iOS

ios,objective-c,string,nsstring,nsurl
I am developing an iOS app and one of the things I need to do it to go over URLs and replace the first protocol section with my own custom protocol. How can I delete the first few characters of a NSString before the "://"? So for example I need...

Add a custom tag to an url in xcode

ios,xcode,nsurl,custom-tag
It's Julian Again. In my project I have around 50 different urls and i need to group them into two groups. So that 25 of them are displayed in VC one and the rest in VC2. I wanted to add a tag, and then based on this tag distinguish the...

How to call HTML file with css, js and images?

javascript,html,ios,zip,nsurl
I am downloading zip file from server. In NSCachesDirectory I have the html file and I would like to know how to run html file with their source files, I have pasted my code. please help me NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *documentsPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"/Lesson-file/Lesson%d",[str_lsn_id...

NSURL returning nil for certain cases

objective-c,nsurl,nsurlsession
I'm creating an NSURL to send as a request to a PHP rest API that I've got setup. Here's my code below: NSMutableString *url = [NSMutableString stringWithFormat:@"http://www.private.com/recievedata.php?item=%@&contact=%@&discovery=%@&summary=%@",__item,__contactDetails,__lostFound,__explain]; //The " ' " in PHP is a special character, so we have to escape it in the URL //The two slashes are...

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

ios,url,nsurl,ios9
So, the new beta SDK of iOS released last night has "App Transport Security" which encourages developers to use https instead of http. In principle, this is a great idea, and I already use https in our staging/production environments. However, I don't have https set up in my local development...

How can I get failed URL from didFailProvisionalNavigation method

ios,iphone,nsurl,wkwebview
I'm trying to display error message for my web view, and I need to know url which is not available, so I implemented delegate method: - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error { [self.addressBar finishLoadingProgressAnimated:YES]; NSLog(@"%@", webView.URL); [self showErrorPageForURL:error.userInfo[NSErrorFailingURLStringKey]]; } but NSErrorFailingURLStringKey is deprecated, so how can I get failed...

How to make HTTP request to php server in Swift iOS

php,ios,swift,nsurl
I am trying to make connection to PHP server using swift but I am getting error don't know how to solve that Here is the code for register tapped button: I am making connection to php server and sending value via post to create a new user in the database....

NSURL breaking port string with colon

ios,escaping,nsurl
I'm trying to add a base url for my networking code, the problem is that this URL gets broken when passing to the URLWithString:relativeToURL: method. This URL has the port i'm using, however, after calling the described, the URL is wrong, not including my current port number. I think this...

UIImage returns null first time, until reloaded? [duplicate]

ios,objective-c,uiimage,nsurl
This question already has an answer here: didReceiveData is not getting all data 2 answers I retrieve NSData from a url, then I try set it to an image. In the console it returns null, however when I request the data and set the image again, the image than...

iOS: Download .TXT file give strange result

ios,swift,nsurlconnection,nsurl
I'm trying to download .txt file that has 5MB size in one website I tried to download file directly and it give the correct size I tried to download via Android DownloadManager.Request and it also give the correct size Except, in iOS, while I tried to download it via NSURLConnection,...

Swift URL Reponse is nil

session,swift,return,nsurl,nil
I have created a custom DataManager class. Inside it I want to fetch data in a method and return an NSData object to convert to JSON afterwards. I have tried to get the data using the completionHandler but no luck: class func fetchData() -> NSData? { var session = NSURLSession.sharedSession(),...

Swift - session.dataTaskWithURL completionHandler never called

swift,nsurl,nsurlsession
I have the following code : let urlPath:String = apiURL + apiVersion + url + "?api_key=" + apiKey let url = NSURL(string: urlPath) let session = NSURLSession.sharedSession() println(url!) let task = session.dataTaskWithURL(url!, completionHandler: {(data, reponse, error) in println("Task completed") // rest of the function... }) The completionHandler function is never...

Swift - Using less than “<” operator in REST api search with NSURLRequest

swift,nsurl,nsurlrequest
I am new to this HTTP request stuff so I apologize if my terminology is not correct. What I am trying to do is search a database using a particular query string. I have used it successfully using curl and partially successfully using NSURLRequest when I don't use the "<"...

unable to display urls in table @ masterViewController

uitableview,swift,nsurl
I'm not able to compile the code in masterViewController as I'm receiving an error UITableView does not have member named textLabel var urls = [NSURL(string: "http://trialwebsite.ucoz.com/GurujiHymns/02_BIGDI_MERI_TAQDIR_KO_Singer_Masoom_Thakur.mp3")!,NSURL(string: "http://trialwebsite.ucoz.com/GurujiHymns/02_BIGDI_MERI_TAQDIR_KO_Singer_Masoom_Thakur.mp3")!,NSURL(string: "http://trialwebsite.ucoz.com/GurujiHymns/03_GURU_JI_TERI_REHMAT_Singer_Sada_Thakur.mp3")!] override func tableView(tableView: UITableView,...

How do I give inputs through NSURL [closed]

ios,swift,nsurl
I am attempting to enter a song title into a website's search bar using NSURL. The website is an MP3 website however it uses the POST function. I also am not sure of how I would go about downloading the MP3 file. I need to select the search button and...

No known class method for selector 'URLAssetWithURL'

ios,objective-c,avfoundation,nsurl,avurlasset
I have an iOS app which uses a lot of different audio files recorded in the app and saved. I have imported AVFoundation framework, however I still get the error: No known class method for selector 'URLAssetWithURL' Here is my code: AVAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:audioFiles[indexPath.row]]]; waveformView.asset = asset;...

objective c - How to tell if an NSURL is formatted as a phone number

ios,nsurl,detect,phone
I have an iOS app with a UITextView that auto detects links and phone numbers. What I want to do is intercept when a link is clicked using this: -(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange and then I need to check whether the URL is a web link or a phone...

URL Variable is not being recognized using NSURL

ios,swift,parsing,web-scraping,nsurl
I am attempting to parse a website, however when I was simply starting to set up my code I got the error, playMusicViewController.swift does not have a member named 'url', as well as the error expected declaration under the task.resume, I did include an import statement as well. let url...

Getting URL of UIImage selected from UIImagePickerController

ios,swift,ios8,uiimagepickercontroller,nsurl
I'm trying to provide a user selection of an image from Photo Library. Thus I'm using UIImagePickerController for selecting. But here comes an issue with getting its initial URL in the file system (I need this for CKAsset). My code. func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { let...

NSURL/NSURLRequest is unexpectedly nil

ios,swift,uiwebview,nsurl,nsurlrequest
I'm trying to load a PDF into a UIWebView, but when using loadRequest, I'm getting the error unexpectedly found nil while unwrapping an Optional. My relevant code is below: let url = NSURL(string: "http://www.urartuuniversity.com/content_images/pdf-sample.pdf")! println(url.fileURL) println("The URL is \(url.absoluteURL!)") let request = NSURLRequest(URL: url) webView.loadRequest(request) The second line of code...

Swift parsing attribute name for given elementName

swift,xml-parsing,nsxmlparser,nsurl,xml-attribute
Here is a part of my URL <cities> <country name="Абхазия"> <city id="37188" region="27028" head="" type="3" country="Абхазия" part="" resort="" climate="">Новый Афон</city> <city id="37178" region="10282" head="" type="3" country="Абхазия" part="" resort="" climate="">Пицунда</city> <city id="37187" region="37187" head="" type="3" country="Абхазия" part="" resort="" climate="">Гудаута</city> <city id="37172" region="10280" head=""...

This NSURL request compiles, but doesn't work as expected. What am I missing?

ios,objective-c,xcode,boolean,nsurl
I'm currently taking a course in iOS development. I've created a basic web browser that can handle an URL that's entered and will add "http://" if the user doesn't add it. With the code below, the user enters text in textField, the app loads a webpage. I've been tasked with...

Swift - UILabel from URL

ios,swift,uilabel,nsurl
I wanted to know if it's possible to load the text in a label from a URL. I was going to try and use NSURL to pull in a .txt file stored online. Would anyone know how to implement this with swift? Thanks...

NSURL URLWithString is shortening very long strings with an ellipsis “…”, creating invalid NSURL objects

ios,nsstring,nsurl
I am trying to use NSURL URLWithString to create an NSURL object from a potentially very long file path with a very long file name. When I convert the file path to an NSURL object using URLWithString, the path gets shortened and an ellipsis " ... " is put in...

Unsupported URL on ios 8

ios8,nsurl,nsurlrequest
I'm trying to fetch a json from google places with the following code: NSString *query = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=%i&types=%@&sensor=true&key=%@", center.latitude, center.longitude, rad, types, kGOOGLE_API_KEY]; NSLog(@"%@",query); NSURL *googleRequestURL=[NSURL URLWithString:query]; [NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:googleRequestURL] queue:[[NSOperationQueue alloc] init]...

Parsing JSON into a usable format

swift,nsarray,nsdictionary,nsurl
I'm currently downloading data from a server and I'm not sure how to get the response that I'm getting back into the format that's expected by the method that I'm working with. Could someone guide me on what I would need to do to get all of the items in...

Using NSNumber numberWithBool in Swift

swift,ios8,nsurl,nsnumber
I submitted my Version 2 of my app for review and it got rejected due to a high backup to iCloud - wasn't aware of this as I only have to pics in my app but anyway. Now I try to convert that code NSError *error = nil; NSURL *databaseUrl...

Checking if an NSURL is instantiated in Swift vs. Objective-C

objective-c,swift,core-data,nsurl
I'm presently taking an iOS development course. As an assignment, I'm tasked with enabling iCloud on a project. I've found Tim Roadley's post to be helpful in explaining the process. The wrinkle: I've built my project in Swift. In particular, one of the "checks" Mr. Roadley built in to check...